void bfs(起始点) {
将起始点放入队列中;
标记起点访问;
while (如果队列不为空) {
访问队列中队首元素x;
删除队首元素;
for (x 所有相邻点) {
if (该点未被访问过且合法) {
将该点加入队列末尾;
}
}
}
队列为空,广搜结束;
}
下面继续使用bfs来实现迷宫游戏。
用 dfs 求解迷宫最短路有一个很大的缺点,需要枚举所有可能的路径,可能的搜索方案数量会非常多,用 dfs 搜索显然效率会很低。而借助 bfs 来求解迷宫游戏。由于 bfs 是分层搜索,因此,第一次搜索到终点的时候,当前搜索的层数就是最短路径的长度。
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int n, m;
string maze[110];
bool vis[110][110];
int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
bool in(int x, int y) {
return 0 <= x && x < n && 0 <= y && y < m;
}
struct node {
int x, y, d;
node(int xx, int yy, int dd)
{
x = xx;
y = yy;
d = dd;
}
};
int bfs(int sx, int sy)
{
queue<node> q;
q.push(node(sx, sy, 0));
vis[sx][sy] = true;
while (!q.empty())
{
node now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int tx = now.x + dir[i][0];
int ty = now.y + dir[i][1];
if (in(tx, ty) && maze[tx][ty] != '*' && !vis[tx][ty])
{
if (maze[tx][ty] == 'T')
{
return now.d + 1;
}
else
{
vis[tx][ty] = true;
q.push(node(tx, ty, now.d + 1));
}
}
}
}
return -1;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
cin >> maze[i];
}
int x, y;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (maze[i][j] == 'S')
{
x = i, y = j;
}
}
}
cout << bfs(x, y) << endl;
return 0;
}