思路
前面我们已经接触过了迷宫游戏,粗学会了如何使用dfs来解决迷宫最短路问题。用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;
}
//记录下x ,y 步数d的状态
struct node{
int x,y,d;
node(int xx,int yy,int dd){
x=xx;
y=yy;
d=dd;
}
};
//(sx,sy)起点的坐标
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;//没有访问到终点,返回-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;
}