Backtracking: Similar to Valid Sudoku, iterate each possible value for every blank, check if valid and recursively call the function to check next blank.
class Solution {
public:
bool isValid(vector<vector<char> > &board, int x, int y)
{
for(int i=0;i<9;i++) {
if(board[x][i]==board[x][y] && i!=y)
return false;
if(board[i][y]==board[x][y] && i!=x)
return false;
}
int sx=x/3;sx*=3;
int sy=y/3;sy*=3;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(board[sx+i][sy+j]==board[x][y]) {
if(sx+i==x && sy+j==y) continue;
return false;
}
return true;
}
bool solveSudoku(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) && solveSudoku(board))
return true;
board[i][j]='.';
}
return false;
}
}
}
return true;
}
};