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...
class Solution {
public:
/*algorithm: DFS
*/
void solveSudoku(vector<vector<char> > &board) {
dfs(board, 0, 0);
}
bool dfs(vector<vector<char> > &board, int x, int y) {
if (x == 9) return true;
if (y >= 9) return dfs(board, x + 1, 0);
if (board[x][y] == '.') {
for (int k = 1; k <= 9; ++k) {
board[x][y] = k + '0';
if (isValid(board, x , y)) {
if (dfs(board, x, y + 1)) return true;
}
board[x][y] = '.';
}
} else {
return dfs(board, x, y + 1);
}
return false;
}
bool isValid(vector<vector<char> > &board, int x, int y) {
char c = board[x][y];
for (int col = 0; col < 9; ++col) {
if (col != y && c == board[x][col]) return false;
}
for (int row = 0; row < 9; ++row) {
if (row != x && c == board[row][y]) return false;
}
int topx = x/3*3,topy=y/3*3;
for (int row = topx; row < topx+3; ++row) {
for (int col = topy; col < topy+3; ++col) {
if ((row != x || col != y) && c == board[row][col]) return false;
}
}
return true;
}
};