#include<stdio.h>int fx[8]={1,2,2,1,-1,-2,-2,-1}; int fy[8]={2,1,-1,-2,-2,-1,1,2}; int x,y,dep;int count=0;int n=5;int m=5;int a[5][5];int check(int x,int y);void find(int x,int y,int dep);void output();int main(){ int i,j; int dep=1;//记录走过的点的个数 scanf("%d,%d",&x,&y); if(x<0||x>(n-1)||y<0||y>(m-1)){ printf("The data is wrong.\n"); } else{ for(i=0;i<n;i++){ for(j=0;j<m;j++){ a[i][j]=0; } }//所有位置都未走过 } a[x][y]=1; find(x,y,2); if(count==0){ printf("There is no solution"); } else printf("Total count=%d\n",count); return 0; } int check(int x,int y){ int flag=1; if (x<0||x>(n-1)||y<0||y>(m-1)){ flag=0;} if (a[x][y]!=0){ flag=0;} return flag;}//判断是否在范围内的函数 void find(int x,int y,int dep){ int i,xx,yy; for(i=0;i<8;i++){ xx=x+fx[i]; yy=y+fy[i]; if (check(xx,yy)==1){ a[xx][yy]=dep; if (dep==n*m){ output(); } else find(xx,yy,dep+1); a[xx][yy]=0;//回溯 }//判断是否出界或者是否走过 }} void output(){ count++; printf("The count=%d\n",count); int i,j; for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("%d ",a[i][j]);//输出走过的位置 } printf("\n"); }}
添加回答
举报
0/150
提交
取消