C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
BFS
$从起点出发,每次判断一下上下左右四个格子,符合条件则加入队尾,直至到达终点$
$如果无法到达终点,返回-1$
$\color{red}{样例模拟:}$
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#define x first
#define y second
using namespace std;
const int N = 210;
typedef pair<int, int> pii;
int n, m;
char g[N][N]; // 存储迷宫矩阵
int dist[N][N]; // 判重
int bfs(pii start, pii end) {
queue<pii> q;
memset(dist, -1, sizeof dist); // 把距离初始化为-1,-1表示不可到达
dist[start.x][start.y] = 0;
q.push(start);
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
while (q.size()) { // 队列不为空
auto t = q.front();
q.pop(); // 队头出队,避免死循环
for (int i = 0; i < 4; i ++) { // 上下左右
int x = t.x + dx[i], y = t.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) continue; // 出界
if (g[x][y] == '#') continue; // 障碍物
if (dist[x][y] != -1) continue; // 之前已经遍历过
dist[x][y] = dist[t.x][t.y] + 1;
if (end == make_pair(x, y)) return dist[x][y];
q.push({x, y});
}
}
return -1;
}
int main() {
int T; cin >> T;
while (T --) {
cin >> n >> m;
for (int i = 0; i < n; i ++) cin >> g[i];
pii start, end; // 找一下起点和终点
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
if (g[i][j] == 'S') start = {i, j};
else if (g[i][j] == 'E') end = {i, j};
int distance = bfs(start, end);
if (distance == -1) puts("oop!");
else cout << distance << endl;
}
return 0;
}