Skip to content

Instantly share code, notes, and snippets.

@krisys
Created April 28, 2011 16:49
Show Gist options
  • Save krisys/946735 to your computer and use it in GitHub Desktop.
Save krisys/946735 to your computer and use it in GitHub Desktop.
Sudoku Solver
#include<iostream>
using namespace std;
int sudoku[9][9],ptr[162],xstart[9]={0,3,6,0,3,6,0,3,6}, ystart[9]={0,0,0,3,3,3,6,6,6};
int valid(){
int valid=1;
int hashtable[10];
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
for(int k=j+1;k<9;k++){
if(sudoku[i][j]==0) continue;
if(sudoku[i][j]==sudoku[i][k]){
return 0;
}
}
}
}
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
for(int k=j+1;k<9;k++){
if(sudoku[j][i]==0) continue;
if(sudoku[j][i]==sudoku[k][i]) {
return 0;
}
}
}
}
for(int i=0;i<9;i++){
for(int x=0;x<=9;x++)
hashtable[x]=0;
for(int j=xstart[i];j<xstart[i]+3;j++)
for(int k=ystart[i];k<ystart[i]+3;k++)
hashtable[sudoku[j][k]]++;
for(int x=1;x<=9;x++)
if(hashtable[x]>1) {return 0;}
}
return 1;
}
int main(){
int k,val;
cout<<"Enter the sudoku problem, use 0 for blank:\n"<<endl;
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
cin>>sudoku[i][j];
while(1){
k=0;
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(sudoku[i][j]==0){
ptr[k++]=i;
ptr[k++]=j;
}
if(!valid()) {cout<<"\nIncorrect puzzle\n\n";return 0;}
if(k==0) break;
int i=0;
while(i<(k/2)){
while(sudoku[ptr[2*i]][ptr[2*i+1]]<10){
sudoku[ptr[2*i]][ptr[2*i+1]]++;
if(valid())
break;
}
if(sudoku[ptr[2*i]][ptr[2*i+1]]>9){
sudoku[ptr[2*i]][ptr[2*i+1]]=0;
if(i==0) {
i++;
continue;
}
else {
i--;
continue;
}
}
else i++;
}
}
cout<<endl<<"The solution for the given problem is:\n"<<endl;
for(int i=0;i<9;i++){
for(int j=0;j<9; j++)
cout<<sudoku[i][j]<<" ";
cout<<endl;
}
cout<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment