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
| #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <queue>
#define x first #define y second
using namespace std; using PII = pair<int, int>; const int N = 210;
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); dist[start.x][start.y] = 0; q.push(start); int dx[4] = {0, -1, 1, 0}, dy[4] = {1, 0, 0, -1}; while(q.size()) { auto s = q.front(); q.pop(); for(int i = 0;i < 4;i ++) { int x = s.x + dx[i], y = s.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[s.x][s.y] + 1; if(end == make_pair(x, y)) return dist[x][y]; q.push({x, y}); } } return -1; }
int main() { int t; scanf("%d", &t); while(t --) { scanf("%d%d", &n, &m); for(int i = 0;i < n;i ++) scanf("%s", 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 printf("%d\n", distance); } return 0; }
|