1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| ```
```c++
#include <bits/stdc++.h> using namespace std;
struct Node { int x, y; int step; Node(int x, int y, int step) : x(x), y(y), step(step) {} };
const int N = 1010; int n, m; char g[N][N]; bool st[N][N]; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1};
int bfs(int sx, int sy, int ex, int ey) { queue<Node> q; q.push({sx, sy, 0}); st[sx][sy] = true;
while (!q.empty()) { auto t = q.front(); q.pop();
if (t.x == ex && t.y == ey) return t.step;
for (int i = 0; i < 4; i++) { int x = t.x + dx[i]; int y = t.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) continue; if (g[x][y] == '#' || st[x][y]) continue;
q.push({x, y, t.step + 1}); st[x][y] = true; } }
return -1; }
int main() { cin >> n >> m;
int sx, sy, ex, ey;
for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> g[i][j]; if (g[i][j] == 'S') { sx = i; sy = j; } if (g[i][j] == 'E') { ex = i; ey = j; } } }
int res = bfs(sx, sy, ex, ey); cout << res << endl;
return 0; }
|