zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    思考题13-1.b
    算法导论 第三版 9.3-8
    算法导论第三版思考题8-4
    算法导论第三版思考题8-3.b
    算法导论第三版思考题8-3.a
    算法导论第三版思考题8-2.e
    算法导论 第三版 思考题 7-4
    test
    一个朋友面试时遇到的算法题(怎么组合后得到最大整数)
    监听器模式、观察者模式
  • 原文地址:https://www.cnblogs.com/wintersong/p/5231665.html
Copyright © 2011-2022 走看看