bfs求单源最短路径问题.
由于bfs的层次遍历特性,最先到达终点的路径就是最短路径.
模板题值得一背<(^-^)>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int N = 205;
int T,R,C;//T组用例,R行C列;
char map[N][N];//存放迷宫;
int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};//方向标;
int dist[N][N];//走到(i,j)时的步数dist[i][j];
queue<pair<int,int>> que;
int bfs (int x,int y) {
dist[x][y] = 0;//起点设置为0;
que.push({x,y});//将起点加入队列;
while (!que.empty()) {
pair<int,int> now = que.front();
que.pop();
for (int i = 0;i < 4;i++) {//遍历四个方向;
int m = now.first + dx[i],n = now.second + dy[i];
if (m < 0 || m >= R || n < 0 || n >= C) continue;//走出了迷宫的范围;
if (dist[m][n] != -1 || map[m][n] == '#') continue;//已经走过该位置或者有障碍物;
dist[m][n] = dist[now.first][now.second] + 1;
if (map[m][n] == 'E') return dist[m][n];
que.push({m,n});//满足特判条件且不为终点的点入队列;
}
}
return -1;
}
int main () {
cin >> T;
while(T--) {
//初始化;
memset(dist,-1,sizeof(dist));
while(!que.empty()) que.pop();
cin >> R >> C;
int x,y;
for (int i = 0;i < R;i++) {
for (int j = 0;j < C;j++) {
cin >> map[i][j];
if (map[i][j] == 'S') {
x = i;
y = j;
}
}
}
int step = bfs(x,y);
if (step == -1) cout << "oop!" << endl;
else cout << step << endl;
}
return 0;
}