Created
October 29, 2016 09:46
-
-
Save Sreyas-Sreelal/aea47808b2535ca356e47e141cfc0c92 to your computer and use it in GitHub Desktop.
Sudoku solver using Recursive Backtracking algorithm pawn version
This file contains 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
/* | |
Sudoku solver using | |
Recursive Backtracking algorithm | |
pawn version by Sreyas | |
*/ | |
UAN(a[][9],&i,&j) | |
{ | |
for(i=0;i<9;i++) | |
for(j=0;j<9;j++) | |
if(a[i][j]==0) | |
return 1; | |
return 0; | |
} | |
ROW(a[][9],in,num) | |
{ | |
for(new i=0;i<9;i++) | |
if(a[in][i]==num) | |
return 1; | |
return 0; | |
} | |
COL(a[][9],in,num) | |
{ | |
for(new i=0;i<9;i++) | |
if(a[i][in]==num) | |
return 1; | |
return 0; | |
} | |
GRID(a[][9],i,j,num) | |
{ | |
for(new u=0;u<3;u++) | |
for(new y=0;y<3;y++) | |
if(a[i+u][j+y]==num) | |
return 1; | |
return 0; | |
} | |
safe(a[][9],i,j,num) | |
{ | |
if(!ROW(a,i,num)&&!COL(a,j,num)&&!GRID(a,i-i%3,j-j%3,num)) | |
return 1; | |
return 0; | |
} | |
solve(a[][9]) | |
{ | |
new i,j; | |
if(!UAN(a,i,j)) | |
return 1; | |
for(new k=1;k<=9;k++) | |
{ | |
if(safe(a,i,j,k)) | |
{ | |
a[i][j] = k; | |
if(solve(a)) | |
return 1; | |
a[i][j] = 0; | |
} | |
} | |
return 0; | |
} | |
main() | |
{ | |
//initialize the below matrix with your sudoku assuming empty space as 0 | |
new a[9][9] = | |
{ | |
{0,8,0, 7,1,2, 0,9,0}, | |
{0,0,0, 0,0,0, 7,1,0}, | |
{0,0,0, 0,9,4, 2,6,0}, | |
{0,0,0, 3,6,0, 4,0,5}, | |
{5,0,0, 0,0,0, 0,0,9}, | |
{7,0,6, 0,2,5, 0,0,0}, | |
{0,5,8, 2,7,0, 0,0,0}, | |
{0,1,7, 0,0,0, 0,0,0}, | |
{0,6,0, 9,4,1, 0,5,7} | |
}; | |
if(solve(a)) | |
{ | |
for(new i=0;i<9;i++) | |
{ | |
for(new j=0;j<9;j++) | |
{ | |
printf("%d ",a[i][j]); | |
if((j+1)%3==0)printf(" "); | |
} | |
printf("\n"); | |
if((i+1)%3==0)printf("\n"); | |
} | |
} | |
else printf("NO solution"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment