Knight Moves

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.

题意描述:
求出在一个八乘八的棋盘中从一点到另一点的最小步数,且只能马走日可以每次走八个方向中的一个。

解题思路:

这道题理解了题意,是一道模板题,将next[]数组更改,利用广搜求出结果。

错误分析:

注意输入不能用scanf(“%c%d  %c%d”);会提示运行错误,可以用%s.

#include<stdio.h>
#include<string.h>
struct note
{
	int x;
	int y;
	int s;
};
int main()
{
	struct note que[1010];
	int book[10][10];
	char A,B,C,D;
	char a1[10],a2[10];
	int n,m,i,j,k,x,y,p,q,tx,ty,flag;
	int head,tail;
	int next[8][2]={-2,1,
					-1,2,
					1,2,
					2,1,
					2,-1,
					1,-2,
					-1,-2,
					-2,-1
					};
	while(scanf("%s%s",a1,a2)!=EOF)
	{
		x=a1[1]-'0';
		y=a1[0]-96;
		p=a2[1]-'0';
		q=a2[0]-96;
		memset(book,0,sizeof(book));
		if(x==p&&y==q)
		{
			printf("To get from %s to %s takes 0 knight moves.\n",a1,a2);
		}
		else
		{
			head=1;
			tail=1;
			que[tail].x=x;//将开始坐标加入队列 
			que[tail].y=y;
			que[tail].s=0;
			tail++;
			book[x][y]=1;//记录坐标已走过
			flag=0;
			while(head<tail)
			{
				for(k=0;k<8;k++)
				{
					tx=que[head].x+next[k][0];
					ty=que[head].y+next[k][1];
					if(tx<1||tx>8||ty<1||ty>8)
						continue;
					{
					if(book[tx][ty]==0)//若坐标未走过,加入队列 
						book[tx][ty]=1;
						que[tail].x=tx;
						que[tail].y=ty;
						que[tail].s=que[head].s+1;
						tail++;
					}
					if(tx==p&&ty==q)
					{
						flag=1;
						break;
					}
				}
				if(flag==1)
					break;
				head++;
			}
				printf("To get from %s to %s takes %d knight moves.\n",a1,a2,que[tail-1].s);
		}
		
	}
	return 0;
}