問題
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ù)獨(dú)的正確性:如果正確起意,繼續(xù)枚舉后面的格子;如果不正確变屁,回溯到上一個狀態(tài)眼俊,繼續(xù)枚舉。
要點(diǎn)
backtracking粟关,每一步枚舉之后都驗證一次疮胖,用以剪枝。
時間復(fù)雜度
O(9^m)闷板,但是由于可以邊枚舉邊驗證澎灸,實際的復(fù)雜度要遠(yuǎn)遠(yuǎn)小于這個量級。
空間復(fù)雜度
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;
}
};