- Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the number 0.
You may assume that there will be only one unique solution.
Example
Example 1:
Given a Sudoku puzzle:
Return its solution:
解法1:DFS
注意:
1)从起始条件(0,0)开始,每次往后调用(x, y+1),y越界后进入下一行(x+1,0)。x越界后说明成功得到一个可行解,故返回true。
2) dfs一定要返回boolean。如果是返回void,那么没法知道到底是不是得到了可行解。
3) 该题只要得到第一个可行解就可以了,所以不需要对dfs(x,y)进行x=0…9, y=0…9的循环调用。
class Solution {
public:
/**
* @param board: the sudoku puzzle
* @return: nothing
*/
void solveSudoku(vector<vector<int>> &board) {
dfs(board, 0, 0);
}
private:
bool dfs(vector<vector<int>> &board, int x, int y) {
if (x >= 9) return true;
if (y >= 9) {
return dfs(board, x + 1, 0);
}
//skip the unit if it already has a number
if (board[x][y] != 0) {
return dfs(board, x, y + 1);
}
for (int i = 1; i <= 9; ++i) {
board[x][y] = i;
if (validSudoku(board, x, y, i)) {
//cout<<"i="<<i<<endl;
if (dfs(board, x, y + 1)) return true;
}
board[x][y] = 0;
}
return false;
}
bool validSudoku(vector<vector<int>> &board, int x, int y, int num) {
for (int i = 0; i < 9; ++i) {
if (i != x && board[i][y] == num) return false;
if (i != y && board[x][i] == num) return false;
}
int startX = x / 3 * 3;
int startY = y / 3 * 3;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int newX = startX + i;
int newY = startY + j;
if (newX != x && newY != y && board[newX][newY] == num) return false;
}
}
return true;
}
};