Hdu OJ 时间限制的迷宫体bfs

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1072

有一个迷宫,主角身上有炸弹,炸弹6分钟会爆炸。每次走一格要耗时1分钟。途中有可以重置爆炸时间的点。问是否能安全走到出口。
看到最短时间就想到BFS。这题和CCF的游戏题很类似,都可以重复走路径,每个点和时间有关,重复走但是要时间不一样。重置时间的点最多走一次。
这里可以定义一个结构体node{int x,int y,int t};表示该点的剩余爆炸时间。visit[x][y][t]表示在爆炸剩余时间t的(x,y)时用掉的时间;
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int map[10][10]; int  ans[10][10][10];
int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
int m, n;
struct node
{
    int x, y, t;
};
int bfs(node start)
{
    queue<node> q; node cur,next;
    q.push(start);
    while (q.size())
    {
        cur = q.front(); q.pop();
        if (map[cur.x][cur.y] == 3)
            return ans[cur.x][cur.y][cur.t];
        if (ans[cur.x][cur.y][cur.t] > m*n)
            return -1;
     if (cur.t <= 1)//如果现在时间少于1,下一次走到终点也会爆炸
            continue;
        for (int i = 0; i < 4; i++)
        {
            next.x = cur.x + dir[i][0];
            next.y = cur.y + dir[i][1];            
            if (next.x >= 0 && next.x < m&&next.y >= 0 && next.y < n&&map[next.x][next.y]>0 && cur.t >= 2)//当前时间必须大于等于2,才能继续走
            {            
                if (map[next.x][next.y] == 4)//走完一次不能继续走
                {
                    next.t = 6;
                    map[next.x][next.y] = 0;
                }
                else
                    next.t = cur.t - 1;    //普通的点
                
                if (ans[next.x][next.y][next.t] == 0)表示在该点该时间下并未走过,所以可以放入队列
                {
                    q.push(next);
                    ans[next.x][next.y][next.t] = ans[cur.x][cur.y][cur.t] + 1;
                }
            }
        }
    }
    return - 1;
}
int main()
{
    int t;
    cin >> t; node start;
    while (t--)
    {
        cin >> m >> n; 
        memset(ans, 0, sizeof(ans));
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cin >> map[i][j];
                if (map[i][j] == 2)
                {
                    start.x = i; start.y = j;
                    start.t = 6;
                }
            }
        }
        cout<<bfs(start)<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值