ACM原题描述
Knight Moves
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.
这是ACM的一道题目,”Knight Moves(骑士跳跃)“的大致意思就是从一点从另一点按它规则走最步数,用BFS算法即可实现..
源代码如下:
#include<stdlib.h>
int dir[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{-1,-2},{1,-2}}; //八个可能方向
int flag[8][8]; //标记手否走过
struct node //knigh结构体
{
int x;//横坐标
int y;//纵坐标
int step;//步数
}knight[100],A,B;
int head=0; //队列头尾
int tail=0;
int main()
{
printf(“input the position of knight\n“);
char a,b,c,d;
scanf(“%c%c%c%c”,&a,&b,&c,&d);
int x1=a-‘a’; //起始点
int y1=b-’1′;
int x2=c-‘a’; //目的地
int y2=d-’1′;
knight[tail].x=x1; //初始节点入队
knight[tail].y=y1;
knight[tail].step=0;
tail++;
flag[x1][y1]=1; //标记
while(head!=tail) //队列不空
{
A=knight[head]; //对头出列
head++;
if(A.x==x2&&A.y==y2) //到达
break;
for(int i=0;i<8;i++) //八个方向
{
int tempX=A.x+dir[i][0];
int tempY=A.y+dir[i][1];
if(tempX>=0&&tempX<8&&tempY>=0&&tempY<8&&flag[tempX][tempY]==0)//没走过且 没越界
{
B.x=tempX;
B.y=tempY;
B.step=A.step+1;
knight[tail]=B; //入列
tail++;
flag[tempX][tempY]=1; //已经过
}
}
}
printf(“To get from %c%c to %c%c takes %d knight moves.”,a,b,c,d,A.step);
system(“pause”);
}