zoukankan      html  css  js  c++  java
  • ZOJ 1649

    这题要用BFS去做,要注意的是’x‘,这里可以有优先队列去做,会很简单;

    另一个要注意的是,a只有一个,r可能有很多个,所以可以用a去找最接近的r;

    #include <iostream>
    #include <queue>
    #include "string.h"
    using namespace std;
    struct step{
        int x,y,t;
        void init(int xx,int yy,int tt){
            x=xx;
            y=yy;
            t=tt;
        }
    };
    int n,m,sx,sy;
    bool visited[200][200];
    int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
    char road[200][200];
    bool operator<(step a, step b)
    {
        return a.t > b.t;
    }
    int bfs(){
        memset(visited, 0 , sizeof(visited));
        priority_queue<step> q;
        step start;
        start.init(sx,sy,0);
        q.push(start);
        visited[sy][sx]=1;
        while(!q.empty()){
            step k=q.top();
            q.pop();
            int x=k.x,y=k.y,t=k.t;
            for(int i=0;i<4;i++){
                int nx=x+dir[i][0];
                int ny=y+dir[i][1];
                if(nx<0||nx>m||ny<0||ny>n||visited[ny][nx])continue;
                if(road[ny][nx]!='r'&&road[ny][nx]!='x'&&road[ny][nx]!='.'){continue;}
                if(road[ny][nx]=='r'){return t+1;}
                if(road[ny][nx]=='x'){
                    step s;
                    s.init(nx,ny,t+2);
                    q.push(s);
                    visited[ny][nx]=true;
                    continue;
                }
                step s;
                s.init(nx,ny,t+1);
                q.push(s);
                visited[ny][nx]=true;
            }
        }

        return -1;
    }
    int main(){
        while(cin>>n>>m){
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    cin>>road[i][j];
                    if(road[i][j]=='a'){
                        sx=j;
                        sy=i;

                    }
                }
            }

            int time=bfs();
            if(time==-1)cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
            else cout<<time<<endl;
        }
        return 0;
    }

  • 相关阅读:
    003.Heartbeat MySQL双主复制
    001.常见监控简介
    微服务探索与实践—服务注册与发现
    设计模式之建造者模式
    .NET Core 3.0之深入源码理解Startup的注册及运行
    【译】.NET Core 3.0 Preview 3中关于ASP.NET Core的更新内容
    C#并发编程之异步编程(三)
    设计模式之中介者模式
    设计模式之单例模式
    设计模式之装饰器模式
  • 原文地址:https://www.cnblogs.com/Mr-Xu-JH/p/3851152.html
Copyright © 2011-2022 走看看