註釋寫的很詳細哦
// 深度搜索利用隊列走迷宮,求最短步數
// 題目大意: 有一個N*M的迷宮,地圖上S代表起點,G代表終點,#代表牆無法通過,.代表路
// 求從起點到終點的最短距離,如果無法找到出口則輸出not find。
// 例如:
// input:
// 3 2
// S#G
// ...
// output
// 4
// dfs隱式的利用了棧的特點,多次遞歸與棧一樣後入先出
// 而bfs則利用隊列,先進先出的搜索
#include <iostream>
#include <cstring>
#include <queue>
#include <string>
using namespace std;
typedef pair<int, int> P; // 方便
const int INF = 10000000; // 表示未訪問過的點的值
const int MAX_N = 100; // 最大地圖的長寬
char maze[MAX_N][MAX_N + 1]; // 模擬地圖
int N, M; // 代表N行M列
int sx, sy; // S的位置座標
int gx, gy; // G的位置座標
int d[MAX_N][MAX_N]; // 記錄當前步數,爲訪問過爲INF
// 代表上下左右四個方向
int dx[4] = { 1, 0, -1, 0}, dy[4] = { 0, 1, 0, -1};
int bfs();
int main()
{
cin >> N >> M;
for(int i = 0; i < N; i++)
{
string str;
cin >> str;
for(int j = 0; j < M; j++)
{
maze[i][j] = str[j];
if(maze[i][j] == 'S') // 找到起點位置
{
sx = i;
sy = j;
}
if(maze[i][j] == 'G') // 找到結束位置
{
gx = i;
gy = j;
}
}
}
int ans = bfs();
if(ans == INF)
cout << "can't find " << endl;
else
cout << ans << endl;
return 0;
}
// 返回(sx,sy)到(gx,gy)的最短距離
// 如果無法到達,則返回INF
int bfs()
{
// 創建隊列,用於存放座標點
queue<P> que;
// 初始化d數組
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
d[i][j] = INF;
// 將起點加入隊列
que.push(P(sx, sy));
// 將起點的距離設爲0
d[sx][sy] = 0;
// 如果隊列的長度爲0則結束循環
while(que.size())
{
P p = que.front(); // 取出隊列最前端的元素
que.pop(); // 彈出隊列最前端的元素
if(p.first == gx && p.second == gy) // 如果取出的元素是終點,則退出循環
break;
// 四方向循環判斷,順序爲右下左上
for(int i = 0; i < 4; i++)
{
int nx = p.first + dx[i], ny = p.second + dy[i];
// 判斷該位置是否可以移動即是否訪問過
if(nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx][ny] != '#' && d[nx][ny] == INF)
{
// 如果符合條件則加入隊列,並且該位置的距離加1
que.push(P(nx, ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}
// 返回終點所需的步數
return d[gx][gy];
}