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.
Statistic | Submit | Discuss | Note
#include<queue> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int dir[8][2] = { {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2} }; char mat[10][10]; bool vis[10][10]; struct node { int x,y; int t; }temp1, temp2; queue< node >qu; bool is_legal(int x, int y) { if( x < 1 || x > 8 || y < 1 || y > 8) return false; return true; } int bfs(int sx, int sy, int ex, int ey) { memset( vis, 0, sizeof(vis) ); while( !qu.empty() ) qu.pop(); temp1.x = sx; temp1.y = sy; temp1.t = 0; vis[temp1.x][temp1.y] = 1; qu.push(temp1); while( !qu.empty() ) { temp1 = qu.front(); qu.pop(); if(temp1.x == ex && temp1.y == ey) { return temp1.t; } for(int i = 0; i < 8; i ++) { temp2.x = temp1.x + dir[i][0]; temp2.y = temp1.y + dir[i][1]; if( !is_legal(temp2.x, temp2.y) ) continue; if(vis[temp2.x][temp2.y] == 1) continue; vis[temp2.x][temp2.y] = 1; temp2.t = temp1.t + 1; qu.push(temp2); } } } int main() { char s[3]; char e[3]; while( ~scanf("%s%s", s, e)) { int sx = s[0] - 'a' + 1; int sy = s[1] - '0'; int ex = e[0] - 'a' + 1; int ey = e[1] - '0'; printf("To get from %s to %s takes %d knight moves.\n", s, e, bfs(sx, sy, ex, ey)); } return 0; }