1242 Rescue BFS

#include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,di,dj,ok,ss;
char mapp[210][210];
int vis[210][210];
//应该不止一个朋友
struct node{
    int x,y;
    int step;
    friend bool operator < (node a,node b){

        return a.step > b.step;  //升序
    }
};
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
priority_queue<node> pq;
void  bfs(){
    node temp,next;
    int s,d;
    while(!pq.empty()){
        temp=pq.top();
       // cout<<temp.floor<<" "<<temp.x<<" "<<temp.y<<" "<<temp.step<<endl;
        pq.pop();
        if(temp.x==di&&temp.y==dj)
        {

        }
       for(int i=0;i<4;i++){
        s=temp.x+dir[i][0];
        d=temp.y+dir[i][1];
        if(s==di&&d==dj){
            ok=1;
            ss=temp.step+1;
            break;}
        if(s>=0&&s<n&&d>=0&&d<m&&vis[s][d]==0&&mapp[s][d]!='#'){
            if(mapp[s][d]=='.'){
             next.step=temp.step+1;
            }else if(mapp[s][d]=='x'){
             next.step=temp.step+2;
            }
            next.x=s;
            next.y=d;
            pq.push(next);
            vis[s][d]=1;
        }
       }
      if(ok) break;
    }

}
int main(){
  int si,sj;
    while(cin>>n>>m){
        memset(vis,0,sizeof(vis));
        while(!pq.empty()) pq.pop();
        ok=0;
        ss=0;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++){
                cin>>mapp[i][j];
                if(mapp[i][j]=='a'){di=i;dj=j;}
                if(mapp[i][j]=='r'){si=i;sj=j;}
            }
        node tt;
        tt.x=si;tt.y=sj;tt.step=0;
        vis[si][sj]=1;
        pq.push(tt);

        bfs();

        if(ss) cout<<ss<<endl;
        else  cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
    }
    return 0;
}

 

posted @ 2016-03-01 16:56  咸咸的告别  阅读(156)  评论(0编辑  收藏  举报