【BFS】UVa439 - Knight Moves

国际象棋马走法最短路径
本文介绍了一种使用BFS算法解决国际象棋中马从起点到终点最短路径的问题。通过定义马的可能走法并利用队列进行逐层遍历,最终找到最短路径。

题意
给出国际象棋中马的起点和重点,求最短路。
思路
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 }

 

转载于:https://www.cnblogs.com/kikii233/p/6001413.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值