题目链接

单向bfs就是水题

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <algorithm>
 5 #include <queue>
 6 using namespace std;
 7 const int INF = 0x3f3f3f3f;
 8 const int Max = 300 + 5;
 9 struct Node
10 {
11     int x, y;
12 };
13 int g[Max][Max];
14 int vis[Max][Max];
15 int n, sx, sy, ex, ey;
16 int gx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
17 int gy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
18 bool in_bound(int x, int y)
19 {
20     if (x >= 0 && y >= 0 && x < n && y < n)
21         return true;
22     return false;
23 }
24 int bfs(int sx, int sy)
25 {
26     Node node, temp;
27     node.x = sx;
28     node.y = sy;
29     vis[sx][sy] = 0;
30     queue<Node> q;
31     q.push(node);
32     while (!q.empty())
33     {
34         node = q.front();
35         q.pop();
36         if (node.x == ex && node.y == ey)
37             return vis[ex][ey];
38         for (int i = 0; i < 8; i++)
39         {
40             int fx = node.x + gx[i];
41             int fy = node.y + gy[i];
42             if (in_bound(fx, fy) && vis[fx][fy] > vis[node.x][node.y] + 1)
43             {
44                 temp.x = fx;
45                 temp.y = fy;
46                 vis[fx][fy] = vis[node.x][node.y] + 1;
47                 q.push(temp);
48             }
49         }
50     }
51     return -1;
52 }
53 int main()
54 {
55     int test;
56     scanf("%d", &test);
57     while (test--)
58     {
59         scanf("%d", &n);
60         scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
61         memset(vis, INF, sizeof(vis));
62         printf("%d\n", bfs(sx, sy));
63     }
64     return 0;
65 }
单向bfs

相关文章:

  • 2019-09-02
  • 2021-07-03
  • 2021-09-22
  • 2021-11-21
  • 2022-12-23
  • 2021-11-03
  • 2021-03-09
猜你喜欢
  • 2021-12-24
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
  • 2021-06-12
相关资源
相似解决方案