优先队列+BFS的经典题型。

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
using namespace std;

#define SIZE 201
#define INF 0x0fffffff

const int move[4][2] = {{1,0}, {-1,0}, {0,-1}, {0,1}};
char maze[SIZE][SIZE];
int Time[SIZE][SIZE];
int N, M;
int bx, by, ex, ey;

struct node
{
    friend bool operator< (const node &a, const node &b)  //优先队列 
    {
        return a.step > b.step;
    }
    int x, y;
    int step;
}p, q;


int check(int r, int c)
{
    if(maze[r][c] != '#' && r >= 0 && c >= 0 && r < N && c < M) 
        return 1;
    return 0;
}

int bfs(int bx, int by)
{
    priority_queue<node> Q;
    p.x = bx; p.y = by;
    p.step = 0;
    Q.push(p);
    while(!Q.empty())
    {
        p = Q.top();
        Q.pop();
        for(int i = 0; i < 4; i++)
        {
            q = p;
            q.x += move[i][0];
            q.y += move[i][1];
            if(check(q.x, q.y))
            {
                if(maze[q.x][q.y] == '.' && (q.step+1) < Time[q.x][q.y])
                {
                    q.step++;
                    Q.push(q);
                    Time[q.x][q.y] = q.step;
                }
                if(maze[q.x][q.y] == 'x' && (q.step+2) < Time[q.x][q.y])
                {
                    q.step += 2;
                    Q.push(q);
                    Time[q.x][q.y] = q.step;
                }
                if(q.x == ex && q.y == ey)
                {
                    return ++q.step;
                }
            }
        }
    }
    return -1;
}


int main()
{
    int i, j;
    while(~scanf("%d%d", &N, &M))
    {
        bx = by = ex = ey = -1;
        getchar();
        memset(maze, '#'sizeof(maze));
        for(i = 0; i < N; i++)
        {
            for(j = 0; j < M; j++)
            {
                Time[i][j] = INF;
                scanf("%c", &maze[i][j]);
                if(maze[i][j] == 'r')
                {
                    bx = i;
                    by = j;
                }
                if(maze[i][j] == 'a')
                {
                    ex = i;
                    ey = j;
                }
            }
            getchar();
        }
        int ans = bfs(bx, by);
        if(ans == -1 || ex == -1 || ey == -1 || bx == -1 || by == -1)
        {
            printf("Poor ANGEL has to stay in the prison all his life.\n");
        }
        else
        {
            printf("%d\n", ans);
        }
    }
    return 0;

} 

posted on 2012-08-19 18:54  有间博客  阅读(250)  评论(0编辑  收藏  举报