经典BFS
(BFS) $O(n * m)$
时间复杂度
m * n
C++ 代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 210;
int k, n, m;
char f[N][N];
int st[N][N];
int dx[] = {0, -1 ,0, 1}, dy[] = {-1, 0, 1, 0};
int main()
{
cin >> k;
while(k --)
{
cin >> m >> n;
int a, b;
queue<pair<int, int>> q;
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
{
cin >> f[i][j];
if(f[i][j] == 'S')
q.push({i ,j});
if(f[i][j] == 'E')
a = i, b = j;
}
memset(st, 0, sizeof st);
while(q.size())
{
auto t = q.front();
q.pop();
if(t.first == a && t.second == b)
break;
for(int i = 0; i < 4; i ++)
{
int x = dx[i] + t.first;
int y = dy[i] + t.second;
if(x >= 0 && x < m && y >= 0 && y < n && !st[x][y] && f[x][y] != '#')
{
st[x][y] = st[t.first][t.second] + 1;
q.push({x, y});
}
}
}
if(st[a][b]) cout << st[a][b] << endl;
else cout << "oop!" << endl;
}
return 0;
}