Codeup墓地-1101
src:http://codeup.cn/problem.php?id=1101
1101: 马的移动
时间限制: 1 Sec 内存限制: 32 MB
题目描述
小明很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。
提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。
输入
输入包含多组测试数据。每组输入由两个方格组成,每个方格包含一个小写字母(a~h),表示棋盘的列号,和一个整数(1~8),表示棋盘的行号。
输出
对于每组输入,输出一行“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;
const int maxn=9;
struct node{
int x,y,step;
}Node;
bool inq[maxn][maxn]={false};
int x[8]={2,1,-1,-2,-2,-1,1,2};
int y[8]={1,2,2,1,-1,-2,-2,-1};
int ans=0;
bool judge(int x,int y){
if(x<=0||x>8||y<=0||y>8)return false;
if(inq[x][y]==true)return false;
return true;
}
void BFS(int x1,int y1,int x2,int y2,int step){
queue<node>Q;
Node.x=x1,Node.y=y1,Node.step=step;
Q.push(Node);
inq[x1][y1]=true;
while(!Q.empty()){
node top=Q.front();
Q.pop();
if(top.x==x2&&top.y==y2){
ans=top.step;
return;
}
for(int i=0;i<8;i++){
int newX=top.x+x[i];
int newY=top.y+y[i];
if(judge(newX,newY)){
Node.x=newX,Node.y=newY,Node.step=top.step+1;
Q.push(Node);
inq[newX][newY]=true;
}
}
}
}
int main(){
char x1,y1,x2,y2;
while(scanf("%c%c %c%c",&x1,&y1,&x2,&y2)!=EOF){
getchar();
int xa=x1-'a'+1,xb=x2-'a'+1,ya=y1-'0',yb=y2-'0';
memset(inq,0,sizeof inq);
BFS(xa,ya,xb,yb,0);
printf("To get from %c%c to %c%c takes %d knight moves.\n",x1,y1,x2,y2,ans);
}
return 0;
}