/*
一開始題目沒有看懂,原來是象棋中的跳馬問題你不是喜歡下棋的嗎?可是為何。。。糾結
這是我第一自己獨立寫的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;
}
}