天天看点

南邮 OJ 1383 Knights

Knights

时间限制(普通/Java) :  1000 MS/ 3000 MS          运行内存限制 : 65536 KByte

总提交 : 56            测试通过 : 27 

比赛描述

A friend is doing research on the Traveling Knight Problem (TKP), in which you 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 the opposite is true. 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.

输入

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.

输出

For each test case, print one line saying "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.

提示

undefined

题目来源

Internet

#include<iostream>
#define MAX_N 8
int a[MAX_N][MAX_N];
int dirX[MAX_N] = {-2,-2,-1,-1, 1, 1, 2, 2};
int dirY[MAX_N] = {-1, 1,-2, 2,-2, 2,-1, 1};
int queX[MAX_N*MAX_N];
int queY[MAX_N*MAX_N];
int queStep[MAX_N*MAX_N];
int queHead,queTail;

int main(){
	freopen("test.txt","r",stdin);
	char s1[3],s2[3];
	int x,y,tx,ty,i,step;
	bool flag;
	while(scanf("%s%s",s1,s2)==2){
		memset(a,-1,sizeof(a));					//-1表示没访问
		queHead = queTail = 0;
		flag = 0;
		x = s1[0]-'a';
		y = s1[1]-'1';
		a[x][y] = 0;							//0表示出发点
		queX[queTail] = x;
		queY[queTail] = y;
		queStep[queTail++] = 0;
		if(x==s2[0]-'a' && y==s2[1]-'1'){
			printf("To get from %s to %s takes 0 knight moves.\n",s1,s2);
			continue;
		}
		a[s2[0]-'a'][s2[1]-'1'] = -2;			//-2表示目的地
		while(!flag && queTail >= queHead){
			x = queX[queHead];
			y = queY[queHead];
			step = queStep[queHead++]+1;
			for(i=0; !flag && i<8; i++){
				tx = x+dirX[i];
				ty = y+dirY[i];
				if(tx>=0 && tx<MAX_N && ty>=0 && ty<MAX_N && a[tx][ty]<0){
					if(a[tx][ty]==-2){
						flag = 1;
						break;
					}else{
						queX[queTail] = tx;
						queY[queTail] = ty;
						queStep[queTail++] = step;
						a[tx][ty] = step;
					}
				}
			}
		}
		printf("To get from %s to %s takes %d knight moves.\n",s1,s2,step);
	}
}