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