BFS简单迷宫

常见迷宫:

输入迷宫 启点 终点 然后求最短路径 BFS例题

用dist[][]数组来记录 启点到每个点的最短路径

 1 #include <iostream>
 2 #include <fstream>
 3 #include <stdio.h>
 4 #include <string.h>
 5 #include <queue>
 6 using namespace std;
 7 
 8 const int maxsize = 128;
 9 const int INF = 0xfff3;
10 int m,n;
11 int d[2][4] = { {-1, 0, 1, 0}, {0, 1, 0, -1} };
12 int dist[maxsize][maxsize];//书上方法 : 用dist[m][n]将最短路径储存起来 初始为INF表示无法到达
13 struct Pos
14 {
15     int x,y;
16 }st,ed;
17 char maze[maxsize][maxsize];
18 
19 bool check(int x, int y)
20 {
21     if(x < 0 || x >= m || y < 0 || y >= n) return false;
22     if(maze[x][y] == '#' || dist[x][y] != INF) return false;//!=INF表示可达就已经走到过
23     return true;
24 }
25 int bfs()
26 {
27     for (int i = 0; i < m; i++)
28       for (int j =0 ;j < n; j++)
29         dist[i][j] = INF;
30     queue<struct Pos> que;
31     que.push(st);
32     dist[st.x][st.y] = 0;//自己到自己为0
33     while (!que.empty())
34     {
35         int nx, ny;
36         Pos node = que.front();
37         que.pop();
38         //ans ++;//这里出错 并不是 每次出队都是最短路径中的结点 调试可以发现
39         if(node.x == ed.x && node.y == ed.y) return dist[ed.x][ed.y];
40         for (int i =0 ; i < 4; i++)
41         {
42             nx = node.x + d[0][i];
43             ny = node.y + d[1][i];
44             if (check(nx, ny))
45             {
46                 Pos temp;
47                 temp.x = nx;
48                 temp.y = ny;//这里用pair更好 方便
49                 dist[nx][ny] = dist[node.x][node.y] + 1;
50                 que.push(temp);
51             }
52         }
53     }
54     return -1;
55 }
56 
57 int main()
58 {
59     ifstream cin("in.txt");
60     freopen("in.txt", "r", stdin);
61     scanf("%d%d", &m, &n);
62     getchar();
63     for (int i = 0;i < m; i++)
64     {
65         gets(maze[i]);
66     }
67     for (int i = 0; i < m; i++)
68     {
69         for (int j = 0; j < n; j++)
70         {
71             if (maze[i][j] == 'S')
72             {
73                 st.x = i;
74                 st.y = j;
75             }
76             if (maze[i][j] == 'G')
77             {
78                 ed.x = i;
79                 ed.y = j;
80             }
81         }
82     }
83     int ans = bfs();
84     if (ans == -1) cout << "no way" << endl;
85     else cout << ans << endl;
86 }
87 //对fill 和 memset 还需了解 是在不行就循环填充
88 //用dist记录最短路径 而不是每一次出队ans++
89 //时间复杂度 状态转移是四个方向 每个格至多访问一次 O(4*m*n)
原文地址:https://www.cnblogs.com/oscar-cnblogs/p/6291438.html