
#include <bits/stdc++.h>
using namespace std;
struct nde {
int x, y, t;
} s, t;
int n, m, d[505][505];
char a[505][505];
queue<nde> q;
void bfs() {
memset(d, 0x3f3f3f, sizeof d);
q.push(s);
while (!q.empty()) {
s = q.front();
q.pop();
if (s.x == t.x && s.y == t.y) {
cout << s.t << endl;
return;
}
if (s.t <= d[s.x][s.y]) {
d[s.x][s.y] = s.t;
if ((s.x + 1) > 0 && ((s.x + 1) <= n && (a[s.x + 1][s.y]) != '#'))
q.push({ s.x + 1, s.y, s.t + 1 });
if ((s.y + 1) > 0 && ((s.y + 1) <= m && (a[s.x][s.y + 1]) != '#'))
q.push({ s.x, s.y + 1, s.t + 1 });
if ((s.x - 1) > 0 && ((s.x - 1) <= n && (a[s.x - 1][s.y]) != '#'))
q.push({ s.x - 1, s.y, s.t + 1 });
if ((s.y - 1) > 0 && ((s.y - 1) <= m && (a[s.x][s.y - 1]) != '#'))
q.push({ s.x, s.y - 1, s.t + 1 });
}
}
cout << -1 << endl;
return;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
if (a[i][j] == 'S') {
s.x = i;
s.y = j;
s.t = 0;
}
if (a[i][j] == 'T') {
t.x = i;
t.y = j;
}
}
}
bfs();
return 0;
}
此代码 Memory Limit Exceeded (MLE)