【简单搜索】POJ2251Dungeon Master

来源:互联网 发布:莎莎源码 解压密码 编辑:程序博客网 时间:2024/06/07 02:20

从起点跑到终点进行一遍BFS即可,算是很(ji)裸(chu)的BFS题目,练练手不错。

#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <queue>#define max 100using namespace std;char map[max][max][max];short vis[max][max][max];int dir[6][3] = { {0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0} };int l, r, c;int sx, sy, sfloor, ex, ey, efloor;int ans;struct node{    int floor, x, y,step;};int isture(int x, int y, int z){    if (x < 0 || x >= l || y < 0 || y >= r || z < 0 || z >= c)        return 0;    else if (map[x][y][z] == '#')        return 0;    else if (vis[x][y][z])        return 0;    return 1;}int bfs(){    queue<node>q;    struct node now, next;    now.floor = sfloor;    now.x = sx;    now.y = sy;    now.step = 0;    while (!q.empty()) q.pop();    q.push(now);    vis[sfloor][sx][sy] = 1;    while (!q.empty())    {        now = q.front();        q.pop();        if (now.floor == efloor&&now.x == ex&&now.y == ey)            return now.step;        for (int i = 0;i < 6;i++)        {            next.floor = now.floor + dir[i][0];            next.x = now.x + dir[i][1];            next.y = now.y + dir[i][2];            next.step = now.step + 1;            if (isture(next.floor, next.x, next.y))            {                vis[next.floor][next.x][next.y] = 1;                q.push(next);            }        }    }    return 0;}int main(){    while (cin >> l >> r >> c, l + r + c)     {        for (int i = 0;i < l;i++)        {            for (int j = 0;j < r;j++)            {                cin >> map[i][j];                for (int k = 0;k < c;k++)                {                    if (map[i][j][k] == 'S')                    {                        sfloor = i;                        sx = j;                        sy = k;                    }                    else if (map[i][j][k] == 'E')                    {                        efloor = i;                        ex = j;                        ey = k;                    }                }            }        }        memset(vis, 0, sizeof(vis));        ans = 0;        ans = bfs();        if (ans)            cout << "Escaped in " << ans << " minute(s)." << endl;        else            cout << "Trapped!" << endl;    }}
0 0
原创粉丝点击