【ZOJ1649】Rescue

来源:Rescue

思路:迷宫.pdf(下载

代码:

#include <iostream>
#include <queue>
#define N 202
#define M 202
#define MAX 0x3f3f3f3f
using namespace std;

struct Position
{
    char ch;
    int time;
};
struct Position prison[N][M];
queue<int> que;
int n,m;
int ax,ay;

void Init()
{
    int i,j;
    while(!que.empty())
        que.pop();
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            cin >> prison[i][j].ch;
            if(prison[i][j].ch=='a')
            {
                ax=i; ay=j;
            }
        }
    }

    for(i=0;i<=n+1;i++)
    {
        prison[i][0].ch = '#';
        prison[i][m+1].ch = '#';
    }

    for(j=0;j<=m+1;j++)
    {
        prison[0][j].ch = '#';
        prison[n+1][j].ch = '#';
    }

    for(i=0;i<=n+1;i++)
    {
        for(j=0;j<=m+1;j++)
        {
            prison[i][j].time = MAX;
        }
    }
}

void Go(int x, int y, int time)
{
    switch(prison[x][y].ch)
    {
        case '#': return;
        case 'a': return;
        case 'x': time++;
        case '.':
        case 'r':
            if(time < prison[x][y].time)
            {
                que.push(x); que.push(y);
                prison[x][y].time = time;
            }
            return;
    }
}

void Bfs()
{
    int x,y;
    que.push(ax); que.push(ay);
    prison[ax][ay].time = 0;
    while(!que.empty())
    {
        x = que.front(); que.pop();
        y = que.front(); que.pop();
        Go(x+1, y, prison[x][y].time+1);
        Go(x, y+1, prison[x][y].time+1);
        Go(x-1, y, prison[x][y].time+1);
        Go(x, y-1, prison[x][y].time+1);
    }
}

void Print()
{
    int min = MAX;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(prison[i][j].ch=='r'
               && prison[i][j].time < min)
                min = prison[i][j].time;
        }
    }
    if(min < MAX)
        cout << min << endl;
    else
        cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}

int main()
{
    while(cin >> n >> m)
    {
        Init();
        Bfs();
        Print();
    }
    return 0;
}

 

posted @ 2010-10-11 20:59  屠一刀  阅读(432)  评论(5编辑  收藏  举报