#include<iostream> #include<queue> #include<cstring> #include<stdio.h> using namespace std; struct site { int l, r, ans; }; int vis[9][9];? int Move[8][2] = { {-1,2} ,{-1,-2},{1,2},{1,-2},{2,-1},{2,1},{-2,1},{-2,-1} };//move储存骑士的走法 bool in(int a, int b) { ?? ?return a >= 1 && a <= 8 && b >= 1 && b <= 8; } int main() { ?? ?char a, b; int r1, r2; site cur, next; int k; ?? ?while (cin >> a >> r1 >> b >> r2) { ?? ??? ?bool judge = 0; ?? ??? ?int line1 = (int)a - 96; int line2 = (int)b - 96;//将字母列转化成数字; ?? ??? ?site start = { line1,r1,0 }, end = { line2,r2,0 }; ?? ??? ?memset(vis, 0, sizeof(vis)); ?? ??? ?queue<site>chess; ?? ??? ?chess.push(start); ?? ??? ?vis[start.l][start.r] = 1; ?? ??? ?while (!chess.empty()) { ?? ??? ??? ?cur = chess.front(); ?? ??? ??? ?chess.pop(); ?? ??? ??? ?if (cur.l == end.l && cur.r == end.r) { ?? ??? ??? ??? ?judge = 1; ?? ??? ??? ??? ?k = cur.ans; ?? ??? ??? ??? ?break; ?? ??? ??? ?} ?? ??? ??? ?for (int i = 0; i < 8; i++) { ?? ??? ??? ??? ?next.l = cur.l + Move[i][0]; ?? ??? ??? ??? ?next.r = cur.r + Move[i][1]; ?? ??? ??? ??? ?if (in(next.l, next.r) && vis[next.l][next.r] == 0) { ?? ??? ??? ??? ??? ?next.ans = cur.ans + 1; ?? ??? ??? ??? ??? ?vis[next.l][next.r] = 1; ?? ??? ??? ??? ??? ?chess.push(next); ?? ??? ??? ??? ?} ?? ??? ??? ?}//利用for循环减少代码量 ?? ??? ?} ?? ??? ? ?? ??? ?cout << "To get from " << a << r1 << " to " << b << r2 << " takes " << k<< " knight moves." << endl; ?? ?} }
|