1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 #include <queue> 6 #include <string> 7 using namespace std; 8 9 const int maxn = 500 + 20; 10 int map[9][9]; 11 int cnt; 12 int d[9][9]; 13 string start, over; 14 int dir[8][2] = { { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 }, { -1, -2 }, { -2, -1 } };
//棋盘方向通常会用二维数组来表示方向 15 struct Node 16 { 17 int r, c; // 行,列 18 //int dir; // 方向 19 Node(int r = 0, int c = 0) : r(r), c(c) {} 20 }; 21 22 bool inside(int r, int c) 23 { 24 if (r < 0 || r >= 8 || c < 0 || c >= 8) return false; 25 return true; 26 } 27 28 //start row, start col, over row, over col 29 bool BFS(int sr, int sc, int or, int oc) 30 { 31 queue<Node> Q; 32 memset(d, 0, sizeof(d)); 33 Node u(sr, sc); 34 Q.push(u); 35 while (!Q.empty()) { 36 Node u = Q.front(); Q.pop(); 37 if ((u.r == or) && (u.c == oc)) { //如果找到,就true; 38 return true; 39 } 40 for (int i = 0; i < 8; i++) { 41 Node v = Node(u.r + dir[i][0], u.c + dir[i][1]); 42 if (inside(v.r, v.c) && d[v.r][v.c] == 0) { 43 d[v.r][v.c] = d[u.r][u.c] + 1; 44 Q.push(v); 45 } 46 } 47 } 48 return false; 49 } 50 51 void print_ans(Node u) 52 { 53 cout << "To get from " << start << " to " << over << " takes " << d[u.r][u.c] << " knight moves. "; 54 } 55 56 int main() 57 { 58 while (cin >> start >> over) { 59 memset(map, 0, sizeof(map)); 60 61 int sr = start[0] - 'a', sc = start[1] - '0' - 1, or = over[0] - 'a', oc = over[1] - '0' - 1; 62 BFS(sr, sc, or, oc); 63 print_ans(Node(or, oc)); 64 } 65 return 0; 66 }
总结:通常最短路(最优解)问题会考虑用BFS来进行求解