poj2251 bfs

简单广搜

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

#define M 33

char maze[M][M][M], tmp[M];
int L, R, C, sx, sy, sz;
int dist[M][M][M], step[6][3] = { {1, 0, 0}, {-1, 0, 0}, {0, 0, -1},
                                  {0, 0, 1}, {0, 1, 0}, {0, -1, 0} };
bool visit[M][M][M];

bool judge (int x, int y, int z)
{
    if (x >= 0 && x < L && y >= 0 && y < R && z >= 0 && z < C
        && maze[x][y][z] != '#' && !visit[x][y][z])   return true;
    return false;
}

int bfs ()
{
    queue <int> qx, qy, qz;
    memset (visit, false, sizeof (visit));
    memset (dist, 0, sizeof (dist));
    qx.push (sx); qy.push (sy); qz.push (sz);
    visit[sx][sy][sz] = true;
    while (!qx.empty()) {
         int curx = qx.front();
         int cury = qy.front();
         int curz = qz.front();
         qx.pop(); qy.pop(); qz.pop();
         for (int i = 0; i < 6; i++) {
             int tx = curx + step[i][0];
             int ty = cury + step[i][1];
             int tz = curz + step[i][2];
             if (maze[tx][ty][tz] == 'E')
                return dist[curx][cury][curz] + 1;
             if (judge (tx, ty, tz))
             {

                dist[tx][ty][tz] = dist[curx][cury][curz] + 1;
                visit[tx][ty][tz] = true;
                qx.push (tx); qy.push (ty); qz.push (tz);
             }
         }
    }
    return -1;
}
int main()
{
    while (scanf ("%d%d%d", &L, &R, &C)) {
         if (!L && !R && !C) break;

         bool flag = false;
         getchar();
         for (int i = 0; i < L; i++) {
             for (int j = 0; j < R; j++) {
                gets(maze[i][j]);
                for (int k = 0; !flag && k < C; k++)
                if (maze[i][j][k] == 'S') {
                    sx = i; sy = j; sz = k;
                    flag = true;
                }
             }
             gets(tmp);
         }
         int ans = bfs();
         if (ans < 0) printf ("Trapped!\n");
         else printf("Escaped in %d minute(s).\n", ans);
    }
    return 0;
}



你可能感兴趣的:(c)