AcWing 1101. 献给阿尔吉侬的花束
原题链接
简单
作者:
跟着灿哥学切菜
,
2021-02-09 10:06:04
,
所有人可见
,
阅读 254
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 210;
char g[N][N];
int dist[N][N];
int n, m;
int bfs(PII start) {
queue<PII> q;
q.push(start);
memset(dist, -1, sizeof dist);
dist[start.first][start.second] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (q.size()) {
auto t = q.front();
q.pop();
int x = t.first, y = t.second, d = dist[x][y];
for (int i = 0; i < 4; i ++) {
int a = x + dx[i], b = y + dy[i];
//此时一定要写成g[a][b] != '#', 因为除了这种情况, 还有其余两种情况--"."和 "E"都是可以通行的。
if (a >= 0 && a < n && b >=0 && b < m && g[a][b] != '#' && dist[a][b] == -1) {
dist[a][b] = d + 1;
q.push({a, b});
}
}
}
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (g[i][j] == 'E') {
return dist[i][j];
}
}
}
return -1;
}
int main() {
int T;
cin >> T;
while (T --) {
cin >> n >> m;
PII start;
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
cin >> g[i][j];
if (g[i][j] == 'S') start = {i, j};
}
}
int res = bfs(start);
if (res == -1) puts("oop!");
else cout << res << endl;
}
return 0;
}