bfs,使用C++的queue,300ms。
# include <cstdio> # include <cstring> # include <queue> using namespace std; const int dx[] = {1,1,-1,-1,2,2,-2,-2}; const int dy[] = {2,-2,2,-2,1,-1,1,-1}; struct Pos{int x, y, d;}; char s[5], g[5]; int sx, sy, gx, gy; int bfs(void) { queue <Pos> Q; Pos cur, nst; char vis[9][9]; memset(vis, 0, sizeof(vis)); vis[sx][sy] = 1; cur.x = sx, cur.y = sy, cur.d = 0; Q.push(cur); while (!Q.empty()) { cur = Q.front(); Q.pop(); if (cur.x==gx && cur.y==gy) return cur.d; for (int i = 0; i < 8; ++i) { nst.x = cur.x + dx[i]; nst.y = cur.y + dy[i]; if (1<=nst.x&&nst.x<=8 && 1<=nst.y&&nst.y<=8 && !vis[nst.x][nst.y]) { if (nst.x==gx && nst.y==gy) return cur.d+1; nst.d = cur.d + 1; vis[nst.x][nst.y] = 1; Q.push(nst); } } } // return -1; } void solve(void) { int ans = bfs(); printf("To get from %s to %s takes %d knight moves.\n", s, g, ans); } int main() { while (~scanf("%s%s", s, g)) { sx = s[0]-'a'+1; sy = s[1]-'1'+1; gx = g[0]-'a'+1; gy = g[1]-'1'+1; solve(); } return 0; }