//========================================================================= // //> Author : flowertree //> About : poj 2243 //> Time : 2015.12.28 //> Algorithm : BFS 骑士游历问题 // : 在 8 * 8 方格中一点到一点 马的最少步数 // //========================================================================= #include <iostream> #include <string.h> #include <stdio.h> #include <algorithm> #include <queue> using namespace std; struct node { int x; int y; int steps; }; char start, ended; int s, e; int sx, sy, ex, ey; int Move[8][2] = {-2, 1, -2, -1, -1, 2, -1, -2, 1, 2, 1, -2, 2, 1, 2, -1}; //马的八个方向 bool flag[9][9]; int BFS() //广度优先搜索 { int tempx, tempy; queue<node> q; node t; t.x = sx; t.y = sy; t.steps = 0; flag[sx][sy] = true; q.push(t); while(!q.empty()) { node temp = q.front(); q.pop(); for(int i = 0; i < 8; i++) { tempx = temp.x + Move[i][0]; tempy = temp.y + Move[i][1]; if(tempx < 1 || tempx > 8 || tempy > 8 || tempy < 1) continue; if(!flag[tempx][tempy] && (tempx == ex) && (tempy == ey)) return temp.steps + 1; if(!flag[tempx][tempy]) { flag[tempx][tempy] = true; node n; n.x = tempx; n.y = tempy; n.steps = temp.steps + 1; q.push(n); } } } return -1; } int main() { while(scanf("%c%d %c%d", &start, &s, &ended, &e) != EOF) { getchar(); memset(flag, false, sizeof(flag)); sx = start - 'a' + 1; sy = s; ex = ended - 'a' + 1; ey = e; int temp; if((start == ended) && (s == e)) temp = 0; else temp = BFS(); printf("To get from %c%d to %c%d takes %d knight moves.\n", start, s, ended, e, temp); } system("pause"); return 0; }