http://acm.hit.edu.cn/hoj/problem/view?id=1440
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
struct state {
int x,y;
int step;
};
char s[5],e[4];
int visited[10][10];
int dir[8][2] ={1,2,2,1,-1,2,-2,1,1,-2,2,-1,-1,-2,-2,-1};
queue<state>q;
bool check(state s){
if(s.x>0&& s.y > 0 &&s.x <9&& s.y < 9 &&!visited[s.x][s.y])
return1;
return 0;
}
int bfs(state st){
state now,next;
st.step = 0;
q.push(st);
visited[st.x][st.y] = 1;
while(!q.empty()){
now = q.front();
if(now.x == e[2]&& now.y == e[3])
return now.step;
for(int i = 0; i < 8; i++) {
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
next.step = now.step + 1;
if(check(next)){
q.push(next);
visited[next.x][next.y] = 1;
}
}
q.pop();
}
return 0;
}
int main(){
while(gets(s)){
e[0] =s[0] - 'a' + 1;
e[1] =s[1] - '0';
e[2] =s[3] - 'a' + 1;
e[3] =s[4] - '0';
statestart;
start.x =e[0];
start.y =e[1];
while(!q.empty())
q.pop();
memset(visited, 0, sizeof(visited));
printf("To get from %c%c to %c%c takes %d knightmoves.\n",s[0],s[1],s[3],s[4],bfs(start));
}
return 0;
}