原文链接:https://blog.csdn.net/weixin_44965308/article/details/104928695
广度优先搜索顾名思义就是以迷宫里的无向图某一个点,借助队列,一层一层以该点为中心散开进行搜索,简单的BFS只能显示出最短路径的长度,这里探讨的就是如何实现BFS对最短路径的输出
简单的BFS
通过队列来实现,找到迷宫的起点(S)入队,出队列里面的队首,把队首上下左右相邻的点入队列,一直重复此操作,直到队列里面的所有元素都出队表示该迷宫不存在解,如果在队清空之前找到终点(T)的话,一层一层的遍历,找到的话就一定是最短路了,但是简单的BFS只能通过输出(now.d+1)来表示最短路的步数长度,不能表示出最短路径到底是什么?
#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{//定义node类型的结构体
int x,y,d;//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'){//如果是终点,BFS返回完成
return now.d+1;
}else{//如果不是不返回,标记该点入队继续搜索
vis[tx][ty]=true;
q.push(node(tx,ty,now.d+1));
}
}
}
}
return -1;//队空未找到就返回-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;
}