Knight Moves

来源:互联网 发布:手机软件清除数据 编辑:程序博客网 时间:2024/05/01 08:27

Problem Description
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output
For each test case, print one line saying "To get from xx to yy takes n knight moves.".
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
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.

<span style="font-size:18px;">#include<iostream>#include<queue>#include<stdio.h>#include<string.h>using namespace std;int vis[12][12];int mov[8][2]={-1,2,-1,-2,1,2,1,-2,2,1,2,-1,-2,1,-2,-1};int x1,y1,x2,y2,jump;struct point{int x,y,step;};void bfs(int x,int y){point p,tmp;p.x=x,p.y=y,p.step=0;int i;queue<point>q;for(q.push(p);!q.empty();q.pop()){p=q.front();if(p.x==x2&&p.y==y2){//如果已到达目的点,则输出步数printf("To get from %c%d to %c%d takes %d knight moves.\n",x1-1+'a',y1,x2-1+'a',y2,p.step);return;//return 语句的作用是跳出这个函数,如果到达了目的点,此时return,bfs()函数里的后面的代码不再执行}for(i=0;i<8;i++)//往8个不同的方向扩展{tmp.x=p.x+mov[i][0],tmp.y=p.y+mov[i][1];if(tmp.x>=1&&tmp.x<=8&&tmp.y>=1&&tmp.y<=8&&!vis[tmp.x][tmp.y])//扩展的点如果没有越界或者没被访问过,{vis[tmp.x][tmp.y]=1;//此时应该标记已被访问tmp.step=p.step+1;q.push(tmp);//把当前扩展到的点放入队列,以便后面的扩展}}}}int main(){//freopen("b.txt","r",stdin);char a[3],b[3];while(scanf("%s %s",a,b)==2){memset(vis,0,sizeof(vis));x1=a[0]-'a'+1,x2=b[0]-'a'+1;y1=a[1]-'0';y2=b[1]-'0';vis[x1][y1]=1;jump=100000;bfs(x1,y1);}return 0;}</span>

0 0
原创粉丝点击