算法分析:
一、使用BFS算法解决二维最短路问题
二、BFS算法关键步骤:
1、初始状态入队
2、取出队头元素
3、拓展新节点
4、新节点入队
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue> // 需使用队列实现bfs
using namespace std;
typedef pair<int,int> PII; // 使用PII存储坐标
#define x first
#define y second
const int N = 210;
int r,c;
PII start,_end; // 起点start,终点_end
char g[N][N]; // 存储迷宫地图
int dist[N][N]; // 存储各点到起点start的距离
int dx[4] = {-1,1,0,0}; // 偏移量
int dy[4] = {0,0,-1,1}; // 偏移量
int bfs (PII start,PII _end) // BFS
{
queue<PII> q; // 队列q
// 1、初始状态入队
q.push(start);
memset(dist,-1,sizeof dist);
dist[start.x][start.y] = 0;
while(q.size()) // 当队列q非空时
{
// 2、取出队头元素
PII h = q.front();
q.pop();
for(int i=0;i<4;i++) // 四个方向
{
// 3、拓展新节点
int x = h.x + dx[i];
int y = h.y + dy[i];
if(x<0 || x>=r || y<0 || y>=c) continue; // 越界
if(dist[x][y] != -1) continue; // 之前已经遍历
if(g[x][y] == '#') continue; // 墙壁
dist[x][y] = dist[h.x][h.y] + 1;
if(_end == make_pair(x,y)) return dist[x][y]; // 已经到达终点_end
// 4、新节点入队
q.push({x,y});
}
}
return -1; // 无法到达终点_end
}
int main()
{
int T;
cin >> T;
while(T--)
{
cin >> r >> c;
for(int i=0;i<r;i++) scanf("%s",g[i]);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
if(g[i][j] == 'S') start = {i,j}; // 获取起点start
else if(g[i][j] == 'E') _end = {i,j}; // 获取终点_end
int d = bfs(start,_end); // 调用bfs函数
if(d == -1) cout << "oop!" << endl;
else cout << d <<endl;
}
return 0;
}