zoj 1649 Rescue

题目链接

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=98233#problem/A

题目大意:

Angle 的朋友想去营救Angle,其任务是到Angle的位置,Angle 的朋友向上,下,左,右移动一步用时1个单位时间,杀死警卫需要用1个时间。计算Angle的朋友营救Angle至少需要多长的时间。
“a” 代表Angle的位置。
“.”代表道路。
“r”代表Angle的朋友。
“#”代表墙。
“x”代表警卫

大体思路:

简单的bfs,与之前直接用bool vis[N][M] 不同,这次因为可能出现花费时间为1的点,也可能会出现花费时间为2的点,所以用一个time[N][M]数组作为标记,当time[cury][curx] (当前位置的时间)大于cost(当前位置需要花费的时间)与上一个位置的时间时,表明time[cury][curx]当前位置的时间可以更新。如果小于,则代表不需要要更新,不用将该点加入到队列中。

代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define MAX 100000
int N, M;
char map[205][205];
int Time[205][205];
int x[] = {-1,1,0,0};
int y[] = {0,0,-1,1};
int ax, ay, rx, ry;
void BFS(int ry,int rx)
{
    queue<int> qx;
    queue<int> qy;
    qx.push(rx);
    qy.push(ry);
    Time[ry][rx] = 0;
    while (!qx.empty() && !qy.empty())
    {
        int x1 = qx.front();
        int y1 = qy.front();
        qx.pop();
        qy.pop();
        for (int i = 0; i < 4; i++)
        {
            int x2 = x1 + x[i];
            int y2 = y1 + y[i];
            int cost=0;
            if (x2 >= 0 && x2 < M && y2 >= 0 && y2 < N && map[y2][x2]!='#')
            {
                if (map[y2][x2] == 'a')
                {
                    cost = 1;
                }
                if (map[y2][x2] == '.')
                {
                    cost = 1;
                }
                else if (map[y2][x2] == 'x')
                {
                    cost = 2;
                }
                if (Time[y2][x2]>cost + Time[y1][x1])
                {
                    Time[y2][x2] = cost + Time[y1][x1];
                    qx.push(x2);
                    qy.push(y2);
                }
            }
        }
    }
}
int main()
{
    while (scanf("%d%d", &N, &M) != EOF)
    {
        memset(map,0,sizeof(map));
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                Time[i][j] = MAX;
            }
        }
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                cin >> map[i][j];
                if (map[i][j] == 'a')
                {
                    ax = j;
                    ay = i;
                }
                if (map[i][j] == 'r')
                {
                    rx = j;
                    ry = i;
                }
            }
        }
        BFS(ry,rx);
        if (Time[ay][ax] == MAX)
        {

           cout << "Poor ANGEL has to stay in the prison all his life." << endl;
        }
        else
        {
            printf("%d\n", Time[ay][ax]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值