Sudoku Solver
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.
class Solution {
private:
bool search(vector<vector<char>>& board,int i,int j)
{
unordered_set<int> hash;
for(int k=0;k<9;k++)
if(board[i][k]!='.')
hash.insert(board[i][k]-'0');
for(int k=0;k<9;k++)
if(board[k][j]!='.')
hash.insert(board[k][j]-'0');
for(int x=i/3*3;x<i/3*3+3;x++)
for(int y=j/3*3;y<j/3*3+3;y++)
if(board[x][y]!='.')
hash.insert(board[x][y]-'0');
if(hash.size()==9) return false;
int newi=-1;
int newj=-1;
for(newi=0;newi<9;newi++)
{
for(newj=0;newj<9;newj++)
if((newi!=i || newj!=j) && board[newi][newj]=='.')
{
for(char k='1';k<='9';k++)
if(hash.find(k-'0')==hash.end())
{
board[i][j]=k;
if(search(board,newi,newj)) return true;
}
board[i][j]='.';
return false;
}
}
for(char k='1';k<='9';k++)
if(hash.find(k-'0')==hash.end())
{
board[i][j]=k;
}
return true;
}
public:
void solveSudoku(vector<vector<char> > &board)
{
int x=0;
int y=0;
for(int i=0;i<9;i++)
{
int j;
for(j=0;j<9;j++)
if(board[i][j]=='.')
{
x=i;
y=j;
break;
}
if(j!=9) break;
}
search(board,x,y);
}
};
private:
bool search(vector<vector<char>>& board,int i,int j)
{
unordered_set<int> hash;
for(int k=0;k<9;k++)
if(board[i][k]!='.')
hash.insert(board[i][k]-'0');
for(int k=0;k<9;k++)
if(board[k][j]!='.')
hash.insert(board[k][j]-'0');
for(int x=i/3*3;x<i/3*3+3;x++)
for(int y=j/3*3;y<j/3*3+3;y++)
if(board[x][y]!='.')
hash.insert(board[x][y]-'0');
if(hash.size()==9) return false;
int newi=-1;
int newj=-1;
for(newi=0;newi<9;newi++)
{
for(newj=0;newj<9;newj++)
if((newi!=i || newj!=j) && board[newi][newj]=='.')
{
for(char k='1';k<='9';k++)
if(hash.find(k-'0')==hash.end())
{
board[i][j]=k;
if(search(board,newi,newj)) return true;
}
board[i][j]='.';
return false;
}
}
for(char k='1';k<='9';k++)
if(hash.find(k-'0')==hash.end())
{
board[i][j]=k;
}
return true;
}
public:
void solveSudoku(vector<vector<char> > &board)
{
int x=0;
int y=0;
for(int i=0;i<9;i++)
{
int j;
for(j=0;j<9;j++)
if(board[i][j]=='.')
{
x=i;
y=j;
break;
}
if(j!=9) break;
}
search(board,x,y);
}
};