标签:following code ica git bool 优先 col The rac
觉得这道题更像是一个深度优先搜索+回溯问题。深度优先搜索的部分是,每次填入一个数,只有当这个数是有效且也不会造成数独未来无效的时候,才会继续递归填入下一个数。而回溯的部分是,当填入的数是违反数独规则的,或者在将来使得数独无效,那么就要把填入的数回溯到初始状态。想明白这一点就非常好做了。
Java
class Solution { public void solveSudoku(char[][] board) { check(board); } private boolean check(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == ‘.‘) { for (char p = ‘1‘; p <= ‘9‘; p++) { board[i][j] = p; if (isValid(board, i, j) && check(board)) return true; board[i][j] = ‘.‘; } return false; } } } return true; } private boolean isValid(char[][] board, int i, int j) { for (int p = 0; p < 9; p++) if (i != p && board[i][j] == board[p][j]) return false; for (int p = 0; p < 9; p++) if (j != p && board[i][j] == board[i][p]) return false; int row = 3 * (i / 3); int col = 3 * (j / 3); for (int p = row; p < row+3; p++) for (int q = col; q < col+3; q++) if (p != i && q != j && board[i][j] == board[p][q]) return false; return true; } }
LeetCode 37. Sudoku Solver —— 解数独
标签:following code ica git bool 优先 col The rac
原文地址:https://www.cnblogs.com/tengdai/p/9240889.html