37. Sudoku Solver(js)
Posted mingL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了37. Sudoku Solver(js)相关的知识,希望对你有一定的参考价值。
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:
- Each of the digits
1-9
must occur exactly once in each row. - Each of the digits
1-9
must occur exactly once in each column. - Each of the the digits
1-9
must occur exactly once in each of the 93x3
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; };
以上是关于37. Sudoku Solver(js)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 37 Sudoku Solver(求解数独)
java 37. Sudoku Solver(#)。java