题意
给出国际象棋中马的起点和重点,求最短路。
思路
BFS求最短路
总结
本来不会写BFS,后来看了好多题解都用了队列,所以照着前面例题中的BFS题写了一个,感觉还行,加油。
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 #include <queue> 7 const int maxn = 10; 8 const int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2}; 9 const int dy[] = { 1, 2, 2, 1, -1, -2, -2, -1}; 10 using namespace std; 11 int x1, y1, x2, y2; 12 int vis[maxn][maxn], d[maxn][maxn]; 13 struct Node 14 { 15 int x, y; 16 Node(int x, int y):x(x),y(y){}; 17 }; 18 void bfs(Node t) 19 { 20 queue<Node>q; 21 memset(d, -1, sizeof d); 22 d[t.x][t.y] = 0; 23 q.push(t); 24 while(!q.empty()){ 25 Node u = q.front(); 26 q.pop(); 27 if(u.x == x2 && u.y == y2) return; 28 for(int i = 0; i < 8; i++){ 29 int x = u.x + dx[i], y = u.y + dy[i]; 30 if(!vis[x][y] && x > 0 && x < 9 && y > 0 && y < 9){ 31 vis[x][y] = 1; 32 d[x][y] = d[u.x][u.y] + 1; 33 //if(x == x2 && y == y2) return; 34 q.push(Node(x,y)); 35 } 36 } 37 } 38 39 } 40 int main() 41 { 42 // freopen("in.txt","r",stdin); 43 char a, b; 44 while(scanf("%c %d %c %d", &a, &y1, &b, &y2) != EOF){ 45 getchar(); 46 memset(vis, 0, sizeof vis); 47 x1 = a - 'a' + 1; 48 x2 = b - 'a' + 1; 49 //printf("x1 = %d, x2 = %d\n", x1, x2); 50 Node u(x1, y1); 51 vis[x1][y1] = 1; 52 bfs(u); 53 printf("To get from %c%d to %c%d takes %d knight moves.\n", a, y1, b, y2, d[x2][y2]); 54 } 55 return 0; 56 }