时间限制:
1 Sec
内存限制:
32 MB
题目描述
小明很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。
提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。
输入
输入包含多组测试数据。每组输入由两个方格组成,每个方格包含一个小写字母(ah),表示棋盘的列号,和一个整数(18),表示棋盘的行号。
输出
对于每组输入,输出一行“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.
分析:
bfs求最少移动步数,马走日字即有八种状态
代码
#include <bits/stdc++.h>
using namespace std;
struct node{
char x;
int y,step;
};
int dir[8][2]={{-2,1},{-2,-1},{2,1},{2,-1},{-1,2},{-1,-2},{1,2},{1,-2}};
int main(){
char x1,x2;
int y1,y2;
queue<node> q;
node start,temp;
while(~scanf("%c%d %c%d",&x1,&y1,&x2,&y2)){
getchar();//接收回车符
int vis[150][9];
memset(vis,0,sizeof(vis));
while(!q.empty())//先清空队列
q.pop();
start.x=x1;
start.y=y1;
start.step=0;
q.push(start);
vis[start.x][start.y]=1;
while(!q.empty()){
start=q.front();
q.pop();
if(start.x==x2&&start.y==y2){
printf("To get from %c%d to %c%d takes %d knight moves.\n",x1,y1,x2,y2,start.step);
break;
}
for(int i=0;i<8;i++){
temp.x=start.x+dir[i][0];
temp.y=start.y+dir[i][1];
if(temp.x>='a'&&temp.x<='h'&&temp.y>=1&&temp.y<=8&&vis[temp.x][temp.y]==0){
temp.step=start.step+1;
q.push(temp);
vis[temp.x][temp.y]=1;
}
}
}
}
return 0;
}