Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1. Each of the digits 1-9 must occur exactly once in each row.
2. Each of the digits 1-9 must occur exactly once in each column.
3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character '.’.
Note:
* The given board contain only digits 1-9 and the character '.'.
* You may assume that the given Sudoku puzzle will have a single unique solution.
* The given board size is always 9x9.
DFS。
private boolean dfs(char[][]board, int offset)。返回的布尔值说明这个是不是正确解法的其中一步。
遍历每个格子,碰到可以填的格子的时候,试着填入每个可能的数字。
如果填进去没冲突而且递归最后返回的值是true,那就说明这是成功路上的一步,不要把当前格子改成其他数字了直接返回。
如果每个字符都试了但是从来没有成功返回过到了字符循环的外面,那就说明你之前某一步错了,这不是正确解法的中间路途,请返回false回溯。
细节:
这里的判断是否valid不用和前一题一样写的那么严肃和累赘,因为你是一个一个插进去的,你可以假设前面摆盘都是valid了,你只要考虑当前插入的元素有没有导致冲突即可,不用再全局搜一遍。就好像insertion sort对每个单独步骤的复杂度是降下来的一样。
实现:
class Solution { public void solveSudoku(char[][] board) { dfs(board,0); } private boolean dfs(char[][]board, int offset) { int i = offset / 9, j = offset % 9; if (offset == 81) { return true; } if (board[i][j] != '.') { return dfs(board, offset + 1); } for (char d = '1'; d <= '9'; d++) { board[i][j] = d; if (isValid(board) && dfs(board, offset+1)) { return true; } else { board[i][j] = '.'; } } // P1: 这里是return false不是return true!!因为如果是这里才return的话,那就是前面每种填法最后都走不到填满的状态,也就是都错的,请回溯。这种肯定要有明确回true和明确回false的地方,否则返回boolean值有什么意义。 return false; } private boolean isValid(char[][] board) { for (int i = 0; i < 9; i++) { Set<Character> row = new HashSet<>(); Set<Character> col = new HashSet<>(); Set<Character> cube = new HashSet<>(); for (int j = 0; j < 9; j++) { // scan row if (board[i][j] != '.' && !row.add(board[i][j])) { return false; } // scan col if (board[j][i] != '.' && !col.add(board[j][i])) { return false; } // scan cube int x = i / 3 * 3 + j / 3, y = i % 3 * 3 + j % 3; if (board[x][y] != '.' && !cube.add(board[x][y])) { return false; } } } return true; } }