任务描述
您的一位朋友正在研究旅行骑士周游问题(Traveling Knight Problem,TKP
),这个问题是要在给出的 n
个方格的棋盘上找到骑士访问每个方格一次且仅一次的回路。您的朋友认为这个问题最困难的部分是确定两个给定的方格之间骑士移动的最小步数,一旦解决了这个问题,就很容易找到路线。 当然您知道反之亦然,所以您要为他写一个解决“困难”部分的程序。 请您编写一个程序,输入两个方格 a
和 b
,然后确定骑士从 a
到 b
的最短路线上移动的次数。
编程要求
根据提示,在右侧编辑器补充代码。 注意:gets
函数不安全,请使用其他输入字符串函数。
测试说明
输入说明
输入包含一个或多个测试用例。每个测试用例一行,这一行给出由一个空格分隔的两个方格。一个方格表示为一个字符串,由一个表示棋盘的列的字母(a-h
)和一个表示棋盘的行的数字(1-8
)组成。
输出说明
对每个测试用例,输出一行To get from xx to yy takes n knight moves.
。
平台会对你编写的代码进行测试:
测试输入:
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
预期输出:
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
#include<iostream> #include<stdio.h> #include<cstring> using namespace std; struct note{ int x; int y; int s; };//利用结构体定义x,y,s int main() { struct note mp[70];//最多8*8个地图元素 int a[9][9]={0},book[9][9]={0};//利用book进行标记 int next[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};//定义移动方式 int h,t; int i,j,k,stx,sty,p,q,tx,ty,flag; char c1[10],c2[10]; for(i=1; i<=8; i++) for(j=1; j<=8; j++) a[i][j]=0;//输入地图 while(cin>>c1>>c2) { memset(book,0,sizeof(book));//置零 stx=c1[0]-'a'+1; p=c2[0]-'a'+1; sty=c1[1]-'0'; q=c2[1]-'0';//将字母转换为坐标 if(stx==p&&sty==q)//起点终点相同,输出0 printf("To get from %s to %s takes %d knight moves.\n",c1,c2,0); else { h=1;t=1;//定义头和尾 mp[t].x =stx; mp[t].y =sty; mp[t].s =0; t++; book[stx][sty]=1;//标记为走过,防止重复计入 flag=0; while(h<t) { for(k=0; k<8; k++) { tx=mp[h].x +next[k][0]; ty=mp[h].y +next[k][1];//进行搜索 if(tx<1||tx>8||ty<1||ty>8)//防止搜索到地图外 continue; if(a[tx][ty]==0&&book[tx][ty]==0) { book[tx][ty]=1; mp[t].x =tx; mp[t].y =ty; mp[t].s =mp[h].s +1;//找到就存如 t++; } if(tx==p&&ty==q) { flag=1; break; } } if(flag==1) break; h++; } printf("To get from %s to %s takes %d knight moves.\n",c1,c2,mp[t-1].s ); } } return 0; }