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.

例子

A sudoku puzzle...
...and its solution numbers marked in red.

分析

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

要点

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

时间复杂度

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

空间复杂度

O(1)

代码

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        if (board.empty()) return;
        solve(board);
    }
    
private:
    bool solve(vector<vector<char>>& 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<vector<char>>& 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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容