Created
September 18, 2018 17:32
-
-
Save shubhampateliitm/78264ed77ec6704dc394ec334c268185 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool isfine(vector<vector<int>>& res,int x,int y, int no){ | |
int i,j,k; | |
for( i = 0; i < 9 ; i++ ){ | |
if(res[x][i]==no || res[i][y]==no){ | |
return false; | |
} | |
} | |
for(i=(x/3)*3;i<((x/3)*3)+3;i++){ | |
for(j=(y/3)*3;j<((y/3)*3)+3;j++){ | |
if(res[i][j]==no){ | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
bool sudoku(int xi,int yi, vector<vector<int>>& res){ | |
if(yi==9){ | |
yi = 0; | |
xi = xi + 1; | |
//cout << xi << endl; | |
} | |
if(xi>=9){ | |
return true; | |
} | |
int i,j; | |
for(i=xi;i<res.size();i++){ | |
for(j=yi;j<res.size();j++){ | |
if(res[i][j]==0){ | |
for(int k = 1; k <= 9; k++){ | |
if(isfine(res,i,j,k)){ | |
res[i][j] = k; | |
bool done = sudoku(i,j+1,res); | |
if(done){ | |
return true; | |
} | |
res[i][j] = 0; | |
} | |
} | |
} | |
if(res[i][j]==0){ | |
return false; | |
} | |
} | |
yi = 0; | |
} | |
return true; | |
} | |
void Solution::solveSudoku(vector<vector<char> > &A) { | |
vector<vector<int>> res(A.size(),vector<int>(A[0].size(),0)); | |
int i,j; | |
for(i=0;i<A.size();i++){ | |
for(j=0;j<A[i].size();j++){ | |
if(A[i][j]!='.'){ | |
res[i][j] = A[i][j] - 48; | |
} | |
} | |
} | |
sudoku(0,0,res); | |
for(i=0;i<A.size();i++){ | |
for(j=0;j<A[i].size();j++){ | |
A[i][j] = res[i][j] + 48; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment