hdoj 1242 Rescue(bfs)

【题目大意】:某人a被关在了监狱里,监狱里有路有墙有看守者x,他的朋友们r想去营救他出来,但没前进一个需要消耗时间1,每遇到一个守卫又要花费时间1去杀死他,问最少多少时间可以把a救出来,救不出来输出"Poor ANGEL has to stay in the prison all his life." 


【解题思路】:明显的bfs...我才a有很多朋友的地方wa了一次,看题看不仔细啊。T_T!!.......

                            反过来以a为起点去搜索,找到到所有r所花费的时间即可。

                            这是一道水题,不过鉴于我这是很少用stl的queue写代码,无聊贴一下吧。


【代码】:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long
#define inf 1<<30

struct Tnode{
    int x,y,cnt;
    Tnode(){}
    Tnode(int a,int b,int c){
        x=a,y=b,cnt=c;
    }
};

int n,m;
char mapp[250][250];
int vis[250][250];
int dis[250][250];
int stx[4]={1,-1,0,0};
int sty[4]={0,0,1,-1};
int x,y,xx,yy,ans;

void solve_bfs(){
    queue<Tnode> que;
    ans=inf;
    memset(vis,0,sizeof(vis));
    for (int i=0; i<n; i++)
        for (int j=0; j<m; j++)
            dis[i][j]=inf;
    vis[x][y]=1;
    que.push(Tnode(x,y,0));
    while (!que.empty()){
        Tnode p=que.front();        
        que.pop();
        for (int i=0; i<4; i++){
            Tnode tmp;
            tmp.x=p.x+stx[i];
            tmp.y=p.y+sty[i];
            tmp.cnt=p.cnt+1;
            if (tmp.x>=0 && tmp.x<n && tmp.y>=0 && tmp.y<m && vis[tmp.x][tmp.y]==0 && mapp[tmp.x][tmp.y]!='#' && tmp.cnt<dis[tmp.x][tmp.y]){
                if (mapp[tmp.x][tmp.y]=='x') tmp.cnt++;
                que.push(tmp);
                dis[tmp.x][tmp.y]=tmp.cnt;
                vis[tmp.x][tmp.y]=1;
            }
        }    
    }
    for (int i=0; i<n; i++){
        for (int j=0; j<m; j++)
            if (mapp[i][j]=='r' && ans>dis[i][j]) ans=dis[i][j];
    }
    if (ans==inf) printf("Poor ANGEL has to stay in the prison all his life.\n");
    else printf("%d\n",ans); 
    return ;
}

int main() {
    while (~scanf("%d%d",&n,&m)){
        getchar();
        for (int i=0; i<n; i++){
            for (int j=0; j<m; j++){
                scanf("%c",&mapp[i][j]);
                if (mapp[i][j]=='a') {x=i; y=j;}                
            }
            getchar();
        }
        solve_bfs();        
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值