能给出所有符合标准的答案...
很早前写的了,还是个C风格的,照着书上的迷宫问题写法改的,可能是我至今写过的最规范的程序....
数据的输入,三个数字,逗号隔开,第一个n表示棋盘为n*n的,接下来两个数字表示起点的坐标(1<= x,y<=n),比如 5,3,3
注意:程序没有考虑错误输入的情况..也没有考虑答案过多或者没有答案的相关处理方法,通常答案比较多,所以增加了同目录下的文件写入,方便查看各种组合...
很早的程序,还是VC6下调的..
- #include<stdio.h>
- #include<stdlib.h>
- #define N 20
- typedef struct
- {
- int x,y;
- }CellType;
- typedef struct
- {
- CellType path[N*N];
- int length;
- }KnightPathType;
- void outSolution(short int knight[][N],int n);
- void trySolution(short int knight[][N],int n,CellType cur,KnightPathType knightPath);
- void knightSolution(short int knight[][N],int n,CellType first);
- int main(void)
- {
- short int knight[N][N]={0};
- //printf("%d %d %d/n",knight[12][3],knight[2][4],knight[5][2]);//调试代码,看是否全赋上初值0;
- int n;
- CellType first;
- scanf("%d,%d,%d", &n ,&first.x ,&first.y );
- first.x--;
- first.y--;
- knightSolution(knight,n,first);
- printf("执行结束");
- system("PAUSE");
- return 0;
- }
- void knightSolution(short int knight[][N],int n,CellType first)
- {
- KnightPathType knightPath;
- knightPath.length=0;
- knightPath.path[knightPath.length].x=first.x;
- knightPath.path[knightPath.length].y=first.y;
- knight[first.y][first.x]=1;
- knightPath.length++;
- trySolution(knight,n,first,knightPath);
- }
- void trySolution(short int knight[][N],int n,CellType cur,KnightPathType knightPath)
- {
- int i;
- int xShift[8]={-2,-2,-1,-1,1,1,2,2};
- int yShift[8]={-1,1,-2,2,-2,2,-1,1};
- CellType adjCell;
- if(knightPath.length==n*n)
- {
- outSolution(knight,n);
- }
- else
- {
- for(i=0;i<8;i++)
- {
- adjCell.x=cur.x+xShift[i];
- adjCell.y=cur.y+yShift[i];
- if(adjCell.x>=0 && adjCell.x<n && adjCell.y>=0 && adjCell.y<n && (knight[adjCell.y][adjCell.x]==0) )
- {
- knightPath.path[knightPath.length].x =adjCell.x;
- knightPath.path[knightPath.length].y =adjCell.y;
- knightPath.length++;
- knight[adjCell.y][adjCell.x]=knightPath.length;
- trySolution(knight,n,adjCell,knightPath);
- knightPath.length--;
- knight[adjCell.y][adjCell.x]=0;
- }
- }
- }
- }
- void outSolution(short int knight[][N],int n)
- {
- static int num=0;
- int i,j;
- FILE *pFile;
- if( (pFile=fopen("result.txt","at+"))==NULL )
- {
- printf("打开文件失败/n任意键退出。。。/n");
- getchar();
- exit(1);
- }
- fprintf(pFile,"第%d条路径:/n",++num);
- printf("第%d条路径:/n",num);
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("%3d",knight[i][j]);
- fprintf(pFile,"%3d",knight[i][j]);
- }
- printf("/n");
- fprintf(pFile,"/n");
- }
- fclose(pFile);
- }