37. Sudoku Solver

问题

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

例子

37. Sudoku Solver_第1张图片
A sudoku puzzle...
37. Sudoku Solver_第2张图片
...and its solution numbers marked in red.

分析

backtracking,从左上到右下,枚举每个空白格子的数字(1-9),然后使用Valid Sudoku的方法验证数独的正确性:如果正确,继续枚举后面的格子;如果不正确,回溯到上一个状态,继续枚举。

要点

backtracking,每一步枚举之后都验证一次,用以剪枝。

时间复杂度

O(9^m),但是由于可以边枚举边验证,实际的复杂度要远远小于这个量级。

空间复杂度

O(1)

代码

class Solution {
public:
    void solveSudoku(vector>& board) {
        if (board.empty()) return;
        solve(board);
    }
    
private:
    bool solve(vector>& board) {
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[0].size(); j++) {
                if (board[i][j] == '.') {
                    for (char c = '1'; c <= '9'; c++) {
                        if (isValid(board, i, j, c)) {
                            board[i][j] = c;
                            if (solve(board))
                                return true;
                            else
                              board[i][j] = '.';  
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }
    
    bool isValid(const vector>& board, int row, int col, int c) {
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == c || 
                board[i][col] == c ||
                board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false;
        }
        return true;
    }
};

你可能感兴趣的:(37. Sudoku Solver)