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 digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid.
The '.'
character indicates empty cells.
方法:
递归加回溯法
public class SudokuSolver { private boolean[][] row = new boolean[9][9]; private boolean[][] col = new boolean[9][9]; private boolean[][][] block = new boolean[3][3][9]; private boolean valid = false; private List<int[]> spaces = new ArrayList<>(); public void solveSudoku(char [][] board){ for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ if(board[i][j] == '.'){ spaces.add(new int[]{i, j}); }else{ int digit = board[i][j] - '0' - 1; row[i][digit] = col[j][digit] = block[i / 3][j / 3][digit] = true; } } } dfs(board , 0); } public void dfs(char[][] board, int pos){ if(pos == spaces.size()){ valid = true; return; } int [] space = spaces.get(pos); int i = space[0], j = space[1]; for (int digit = 0; digit < 9 && !valid; ++digit){ if(!row[i][digit] && !col[j][digit] && !block[i / 3][j / 3][digit]){ row[i][digit] = col[j][digit] = block[i / 3][j / 3][digit] = true; board[i][j] = (char)(digit + '0' + 1); dfs(board, pos + 1); row[i][digit] = col[j][digit] = block[i / 3][j / 3][digit] = false; } } } }
参考链接:
https://leetcode.com/problems/sudoku-solver/
https://leetcode-cn.com/problems/sudoku-solver/