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,從左上到右下,枚舉每個空白格子的數(shù)字(1-9),然后使用Valid Sudoku的方法驗證數(shù)獨的正確性:如果正確,繼續(xù)枚舉后面的格子;如果不正確,回溯到上一個狀態(tài),繼續(xù)枚舉。

要點

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;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容