Created
September 2, 2011 14:53
-
-
Save rohit-nsit08/1188820 to your computer and use it in GitHub Desktop.
knight's tour problem
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
| #include<stdio.h> | |
| #define true 1 | |
| #define false 0 | |
| #define size 8 | |
| //function declarations | |
| void printsolution(int sol[][size]); | |
| int solvetour(int x,int y, int nextmove, int sol[][size],int a[],int b[]); | |
| int issafe(int x, int y, int sol[][size]); | |
| //main starts | |
| int main() | |
| { | |
| int i,j; | |
| int sol[size][size]; | |
| int a[8] = {2,-1, -2, 1, -1, -2, 1, 2}; | |
| int b[8] = {1, 2, -1, -2, -2, 1, 2,-1}; | |
| // possible 8 movement of the knight | |
| for(i=0;i<size;i++) //initializing the solution array | |
| for(j=0;j<size;j++) | |
| sol[i][j]=0; | |
| if(solvetour(0,0,1,sol,a,b)==false) | |
| { | |
| printf("no tour exists"); | |
| return false; | |
| } | |
| else | |
| { | |
| printsolution(sol); | |
| } | |
| return 0; | |
| } | |
| int solvetour(int x,int y, int nextmove, int sol[][size],int a[],int b[]) | |
| { | |
| int i,xnew,ynew; | |
| if(nextmove == size*size)return true; // base condition | |
| else | |
| { | |
| // work starts here, | |
| for(i=0;i<size;i++) | |
| { | |
| xnew = x+a[i]; //select next move | |
| ynew = y+b[i]; | |
| if(issafe(xnew,ynew,sol)) | |
| { | |
| sol[xnew][ynew] = nextmove; | |
| if(solvetour(xnew,ynew,nextmove+1,sol,a,b)) | |
| return true; | |
| else | |
| sol[xnew][ynew] = 0; // backtrack | |
| } | |
| } | |
| } | |
| return false; | |
| } | |
| int issafe(int x, int y, int sol[][size]) | |
| { | |
| if((x>=0)&&(x<size)&&(y>=0)&&(y<size)&&sol[x][y]==0) | |
| return true; | |
| return false; | |
| } | |
| void printsolution(int sol[][size]) | |
| { | |
| int i,j; | |
| for(i=0;i<size;i++) | |
| { | |
| for(j=0;j<size;j++) | |
| { | |
| printf("%2d ",sol[i][j]); | |
| } | |
| printf("\n"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment