首页 > 代码库 > HDU1242 (BFS搜索中使用优先队列)

HDU1242 (BFS搜索中使用优先队列)

一道用到优先队列的BFS题目

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <queue>
#define N 201
using namespace std;
char maze[N][N];
int a,b,anw;
bool visit[N][N];
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
int sx,sy,ex,ey;
struct node{
    int x,y;
    int t;
    friend bool operator<(node n1,node n2){
        return n1.t>n2.t;
    }
};
bool judge(int x,int y)
{
    if( x<0 || y<0 || x>=a || y>=b )
        return 1;
    if( visit[x][y] )
        return 1;
    if( maze[x][y]=='#' )
        return 1;
    return 0;
}
int bfs(){
        priority_queue<node> myque;
        memset(visit,0,sizeof(visit));
        node now,next,temp;
        now.x=sx;
        now.y=sy;
        now.t=0;
        visit[sx][sy]=true;
        myque.push(now);
        while(!myque.empty()){
            temp=myque.top();
            myque.pop();
            if(maze[temp.x][temp.y]=='r') {
                return temp.t;
            }
            for(int i=0;i<4;i++){
               int nx=temp.x+dir[i][0];
               int ny=temp.y+dir[i][1];
               if(judge(nx,ny)) {
                    continue;
               }
                next.x = nx;
                next.y = ny;
               if(maze[next.x][next.y]=='x') {
                  next.t=temp.t+2;
               }
               else {
                   next.t=temp.t+1;
               }
               visit[temp.x][temp.y]=true;
               myque.push(next);
               }
        }
        return -1;
}
int main(){
        while(scanf("%d%d",&a,&b)!=EOF){
            anw=0;
            for(int i=0;i<a;i++){
                for(int j=0;j<b;j++){
                    cin>>maze[i][j];
                    if(maze[i][j]=='a') {
                        sx=i;
                        sy=j;
                    }
                }
            }
            anw=bfs();
            if(anw==-1) printf("Poor ANGEL has to stay in the prison all his life.\n");
            else printf("%d\n",anw);
        }
        return 0;
}