37. Sudoku Solver
Total Accepted: 48148
Total Submissions: 195066
Difficulty: Hard
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.
Subscribe to see which companies asked this question
Have you met this question in a real interview?
解数独。
经典问题了
DFS+回溯
把以前POJ那道题的代码稍稍改改就过了。
class Solution {
private:
bool issolve=false;
vector<vector<char>> graph;
public:
bool isOk(int x,int y,int value)
{
for(int i=0;i<9;i++)
if(graph[i][y]-'0'==value||graph[x][i]-'0'==value)
return false;
int sx=x/3*3,sy=y/3*3;
for(int i=sx;i<sx+3;i++)
for(int j=sy;j<sy+3;j++)
if(graph[i][j]-'0'==value)
return false;
return true;
}
void dfs(int k){
if(k==81)
{
issolve=true;
return;
}
int x=k/9,y=k%9;
if(graph[x][y]!='.')
dfs(k+1);
else
for(int i=1;i<=9;i++)
if(isOk(x,y,i))
{
graph[x][y]=i+'0';
dfs(k+1);
if(issolve)
return;
graph[x][y]='.';
}
}
void solveSudoku(vector<vector<char>>& board) {
graph=board;
dfs(0);
board=graph;
}
};