骑士的移动 Knight Moves
题面翻译
输入8*8的国际象棋棋盘上的2个格子(列:ah,行:18),求马至少多少步从起点(键盘输入的第一个位置)跳到终点(键盘输入的第二个位置)。
感谢 @陶文祥 提供的翻译。
题目描述
输入格式
输出格式
样例 #1
样例输入 #1
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
样例输出 #1
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 aa{
int x,y;
int ans;
}a;
queue <aa> q;
int dx[10]={-1,1,-1,1,-2,2,-2,2};
int dy[10]={-2,2,2,-2,-1,1,1,-1};
bool bo[10][10];
int x,y,xx,yy,xxx,yyy;
char ch;
string sx,sy;
int main()
{
while(cin>>sx)
{
cin>>sy;
x=sx[0]-'a'+1;
y=sx[1]-'0';
xxx=sy[0]-'a'+1;
yyy=sy[1]-'0';
memset(bo,0,sizeof(bo));
bo[x][y]=1;
q.push( (aa) {x,y,0});
while(q.empty()==0)
{
a=q.front();
q.pop();
if(a.x==xxx&&a.y==yyy)
{
cout<<"To get from "<<sx<<" to "<<sy<<" takes "<<a.ans<<" knight moves."<<endl;
break;
}
for(int i=0;i<=7;i++)
{
xx=a.x+dx[i];
yy=a.y+dy[i];
if(xx<=0||yy<=0||xx>8||yy>8)
{
continue;
}
if(bo[xx][yy])
{
continue;
}
bo[xx][yy]=1;
q.push( (aa) {xx,yy,a.ans+1});
}
}
while(q.empty()==0)
{
q.pop();
}
}
return 0;
}