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.
Eddy
这一题并没有什么特别技巧,只不过有两点需要注意一下 1.骑士走的方向是8个方向。2 是s[y]=s1[1]-'1',减去的应该是1,我开始写的是减.0,调试了老半天.
#include<iostream> #include<cstdio> #include<queue> #include<cstring> using namespace std; int ex, ey, sx, sy; int vis[20][20]; int step[20][20]; struct point { int x; int y; }; queue<point>q; int dirx[10] = { -2, -1, 1, 2, -2, -1, 1, 2 }; int diry[10] = { -1, -2, -2, -1, 1, 2, 2, 1 }; int bfs() { while (!q.empty())//为什么要加这一句呢?因为q是全局变量,所以每次用都要置空队列 q.pop(); point temp, head, tt; temp.x = sx; temp.y = sy; vis[sx][sy] = 1; q.push(temp); while (!q.empty()) { head = q.front(); q.pop(); for (int i = 0; i<8; i++) { tt.x = head.x + dirx[i]; tt.y = head.y + diry[i]; if (tt.x<1 || tt.y<1 || tt.x>8 || tt.y>8 || vis[tt.x][tt.y]) continue; vis[tt.x][tt.y] = 1;//标记为访问过 q.push(tt); step[tt.x][tt.y] = step[head.x][head.y] + 1;//记录步数 if (ex == tt.x&&ey == tt.y) return step[ex][ey]; } } } int main() { char s1[10], s2[10]; while (cin >> s1 >> s2) { sx = s1[0] - 'a' + 1; sy = s1[1] - '1' + 1; ex = s2[0] - 'a' + 1; ey = s2[1] - '1' + 1;// memset(vis, 0, sizeof(vis)); memset(step, 0, sizeof(step)); if (sx == ex&&sy == ey)//若起点坐标为之与终点坐标相同则输出0步 printf("To get from %s to %s takes 0 knight moves.\n", s1, s2); else printf("To get from %s to %s takes %d knight moves.\n", s1, s2, bfs()); } return 0; }