# LeetCode Sudoku Solver 回溯

DFS。时间复杂度O(9^4)，空间复杂度O(1)。

class Solution {
private:
bool isValid(vector<vector<char>> &board, int i, int j) {
//check col
for(int row = 0; row < 9; ++row) {
if(row != i && board[row][j] == board[i][j]) {
return false;
}
}
//check row
for(int col = 0; col < 9; ++col) {
if(col != j && board[i][col] == board[i][j]) {
return false;
}
}
//check cube
for(int row = i - i%3; row < i + (3 - i%3); ++row) {
for(int col = j - j%3; col < j + (3 - j%3); ++col) {
if(row == i && col == j) continue;
if(board[row][col] == board[i][j]) {
return false;
}
}
}
return true;
}

bool dfs(vector<vector<char>>& board) {
for(int i = 0; i < 9; ++i) {
for(int j = 0; j < 9; ++j) {
if(board[i][j] == '.') {
for(int k = 1; k <= 9; ++k) {
board[i][j] = '0' + k;
if(isValid(board, i, j) && dfs(board)) {
return true;
}
board[i][j] = '.';
}
return false;
}
}
}
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
dfs(board);
}
};

#### Sudoku Solver -- LeetCode

2014-03-10 03:56:50

#### Sudoku Solver 破解数独 @LeetCode 附DFS感想

2013-11-24 11:00:55

#### Leetcode 37 Sudoku Solver

2013-02-17 21:53:25

#### LeetCode 37 Sudoku Solver (C,C++,Java,Python)

2015-05-19 13:11:05

#### 37. Sudoku Solver Leetcode Python

2015-03-27 04:58:37

#### (Java)LeetCode-37. Sudoku Solver

2016-08-09 21:36:31

#### [leetcode-37]Sudoku Solver(java)

2015-09-01 22:20:17

#### LeetCode Sudoku Solver 数独C++程序

2013-12-05 07:47:18

#### [LeetCode] 037. Sudoku Solver (Hard) (C++)

2015-03-13 19:33:27

#### LeetCode(37) Sudoku Solver

2015-03-23 07:55:02