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
   | #include <queue> #include <stdio.h> #include <string.h> using namespace std;
  struct node {     int x, y, step; };
  char map[105][105]; int vis[105][105]; int to[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; int n, m, sx, sy, ex, ey, ans;
  int check(int x, int y) {     if (x < 0 || x >= n || y < 0 || y >= m)         return 1;     if (vis[x][y] || map[x][y] == '#')         return 1;     return 0; }
  void bfs() {     int i;     queue<node> Q;     node a, next;     a.x = sx;     a.y = sy;     a.step = 0;     vis[a.x][a.y] = 1;     Q.push(a);     while (!Q.empty()) {         a = Q.front();         Q.pop();         if (map[a.x][a.y] == 'E') {             ans = a.step;             return;         }         for (i = 0; i < 4; i++) {             next = a;             next.x += to[i][0];             next.y += to[i][1];             if (check(next.x, next.y))                 continue;             next.step = a.step + 1;             vis[next.x][next.y] = 1;             Q.push(next);         }     }     ans = -1; }
  int main() {     int t;     scanf("%d", &t);     while (t--) {         scanf("%d%d", &n, &m);         int i, j;         for (i = 0; i < n; i++)             scanf("%s", map[i]);         for (i = 0; i < n; i++) {             for (j = 0; j < m; j++) {                 if (map[i][j] == 'S') {                     sx = i;                     sy = j;                 }             }         }         memset(vis, 0, sizeof(vis));         bfs();         printf("%d\n", ans);     }
      return 0; }
   |