标签:棋盘 png modify ali not func solution svg col
37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1-9
must occur exactly once in each row.1-9
must occur exactly once in each column.1-9
must occur exactly once in each of the 9 3x3
sub-boxes of the grid.Empty cells are indicated by the character ‘.‘
.
A sudoku puzzle...
题意:填满剩余数字,使其满足数独
代码如下:
/** * @param {character[][]} board * @return {void} Do not return anything, modify board in-place instead. */ var solveSudoku = function(board) { if(board.length===0 || board.length!==9 || board[0].length!==9) return ; dfs(board,0,0); }; // 判断是否符合要求 /** *1.每一行值各不相同 *2.每一列值各不相同 *3.每个3X3的小棋盘里的值各不相同 */ var isValid=function(board,i,j){ for(let col=0;col<9;col++){ if(col!==j && board[i][j]===board[i][col]) return false; } for(let row=0;row<9;row++){ if(row!==i && board[i][j]===board[row][j]) return false; } for(let row=parseInt(i/3)*3;row<parseInt(i/3)*3+3;row++){ for(let col=parseInt(j/3)*3;col<parseInt(j/3)*3+3;col++){ if((row!==i || col!==j)&&board[i][j]===board[row][col]) return false; } } return true; }; /** *递归遍历,边界判断,逐个数字带入值为‘.‘的方格,判断其是否符合要求 */ var dfs=function(board,i,j){ if(i===9) return true; if(j>=9) return dfs(board,i+1,0); if(board[i][j]===‘.‘){ for(let k=1;k<=9;k++){ board[i][j]=k+‘‘; if(isValid(board,i,j)){ if(dfs(board,i,j+1)) return true; } board[i][j]=‘.‘; } }else{ return dfs(board,i,j+1); } return false; };
标签:棋盘 png modify ali not func solution svg col
原文地址:https://www.cnblogs.com/xingguozhiming/p/10415253.html