/*
一开始题目没有看懂,原来是象棋中的跳马问题你不是喜欢下棋的么?可是为何。。。纠结
这是我第一自己独立写的bfs, 在通过调试,终于改了自己犯的低级的毛病(标记为@的地方)
*/
#include<iostream>//2374758 2010-04-23 14:41:15 Accepted 1372 46MS 292K 1189 B C++ 悔惜晟
#include<queue>
#include<cstdio>
using namespace std;
int map[10][10];
bool hash[10][10];
int si, sj;
int ei, ej;
char str1[5];
char str2[5];
int dir[8][2] = { {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2} };
struct Node
{
int x;
int y;
int t;
};
int bfs(int i, int j)
{
Node P , N;
int k;
N.x = i; N.y = j; N.t = 0;
queue<Node> q;
q.push(N);
hash[i][j] = false;
while(!q.empty())
{
N = q.front();
q.pop();
if(N.x == ei && N.y == ej)
{
cout<<"To get from "<<str1<<" to "<<str2<<" takes "<<N.t<<" knight moves."<<endl;
//cout<<N.t<<endl;
break;
}
for(k = 0; k < 8; k++)
{
int tx = N.x + dir[k][0];
int ty = N.y + dir[k][1];
if( tx >= 1 && tx <= 8 && ty >= 1 && ty <= 8 && hash[tx][ty] )//还有这里以开始也标记错误,不小心写成 !hash[tx][ty]
{
P.x = tx;
P.y = ty;
P.t = N.t + 1;
q.push(P);
hash[P.x][P.y] = false;
}
}
}
return 1;
}
int main()
{
while(scanf("%s%s", str1, str2) != EOF)
{
si = str1[1] - '0';
sj = str1[0] - 96;//@一开始这里写成sj = str1[0] -'0'- 96; 调试之后发现 sj的值变成负数
ei = str2[1] - '0';
ej = str2[0] - 96;
memset(hash, true, sizeof(hash));
bfs(si, sj);
//cout<<endl;
}
}