LeetCode 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. 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 '.'.
 
A sudoku puzzle...
 
...and its solution numbers marked in red.
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.

觉得这道题更像是一个深度优先搜索+回溯问题。深度优先搜索的部分是,每次填入一个数,只有当这个数是有效且也不会造成数独未来无效的时候,才会继续递归填入下一个数。而回溯的部分是,当填入的数是违反数独规则的,或者在将来使得数独无效,那么就要把填入的数回溯到初始状态。想明白这一点就非常好做了。


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;
    }
}

猜你喜欢

转载自www.cnblogs.com/tengdai/p/9240889.html