hdoj 1242 Rescue

20 篇文章 0 订阅

题目大意:一个迷宫,多个朋友去解救一个人,#表示障碍,不能走,r表示朋友,x表示守卫,走到这位置得消耗2个单元,其他只消耗一个单元,a表示要解决的人。求多个朋友解救到这个人的最短时间

解题思路:因为有多个起点,我们可以反过来以a为起点,求到达任意一个r的最短时间。

用宽度优先遍历。。。。但是有x节点,消耗2个时间单元,所以保存每次走过的格子状态,即每个格子当前能到达的最短时间。

宽度优先遍历时,若这个格子节点的值比当前走到的时间长,则更新这个格子,然后扩展这个节点。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

struct node
{
    int x, y, step;
};

const int maxn = 210;

int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int n, m, num, sx, sy, minv;
char prison[maxn][maxn];
int val[maxn][maxn];

bool bfs();

int main()
{
    
    while(scanf("%d %d", &n, &m) != EOF)
    {
        num = 0;
        memset(val, 0, sizeof(val));
        for(int i = 0; i < n; i++)
        {
            scanf("%s", prison[i]);
            for(int j = 0; j < m; j++)
            {
                if(prison[i][j] == 'a')
                {
                    sx = i;
                    sy = j;
                }
                val[i][j] = 0x7fffffff;
            }
            
        }
        val[sx][sy] = 0;
        if(bfs())
            printf("%d\n", minv);
        else
            printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
    
    return 0;
}

bool bfs()
{
    queue<node> que;
    node s, next;
    s.x = sx;
    s.y = sy;
    s.step = 0;
    que.push(s);
    minv = 0x7fffffff;
    while(!que.empty())
    {
        node tmp = que.front();
        que.pop();
        if(prison[tmp.x][tmp.y] == 'r')
            minv = min(minv, tmp.step);
        
        for(int i = 0; i < 4; i++)
        {
            next.x = tmp.x + dir[i][0];
            next.y = tmp.y + dir[i][1];
            next.step = tmp.step + 1;
            if(next.x >= 0 && next.x < n && next.y >=0 && next.y < m && prison[next.x][next.y] != '#')
            {
				if(prison[next.x][next.y] == 'x')
					next.step++;
                if(val[next.x][next.y] > next.step)
                {
                    val[next.x][next.y] = next.step;
                    que.push(next);
                }
            }
        }
    }
    if(minv != 0x7fffffff)
        return true;
    return false;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值