HDU1072 Nightmare(dfs、bfs、记忆化搜索)

本文介绍了一个迷宫逃生问题,目标是在炸弹爆炸前找到出口。通过DFS深度优先搜索和BFS广度优先搜索两种方法实现,考虑了墙壁、起点、终点及炸弹重置点等元素,旨在寻找最短逃生路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ignatius had a nightmare last night. He found himself in a labyrinth with a time bomb on him. The labyrinth has an exit, Ignatius should get out of the labyrinth before the bomb explodes. The initial exploding time of the bomb is set to 6 minutes. To prevent the bomb from exploding by shake, Ignatius had to move slowly, that is to move from one area to the nearest area(that is, if Ignatius stands on (x,y) now, he could only on (x+1,y), (x-1,y), (x,y+1), or (x,y-1) in the next minute) takes him 1 minute. Some area in the labyrinth contains a Bomb-Reset-Equipment. They could reset the exploding time to 6 minutes. 

Given the layout of the labyrinth and Ignatius' start position, please tell Ignatius whether he could get out of the labyrinth, if he could, output the minimum time that he has to use to find the exit of the labyrinth, else output -1. 

Here are some rules: 
1. We can assume the labyrinth is a 2 array. 
2. Each minute, Ignatius could only get to one of the nearest area, and he should not walk out of the border, of course he could not walk on a wall, too. 
3. If Ignatius get to the exit when the exploding time turns to 0, he can't get out of the labyrinth. 
4. If Ignatius get to the area which contains Bomb-Rest-Equipment when the exploding time turns to 0, he can't use the equipment to reset the bomb. 
5. A Bomb-Reset-Equipment can be used as many times as you wish, if it is needed, Ignatius can get to any areas in the labyrinth as many times as you wish. 
6. The time to reset the exploding time can be ignore, in other words, if Ignatius get to an area which contain Bomb-Rest-Equipment, and the exploding time is larger than 0, the exploding time would be reset to 6. 

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. 
Each test case starts with two integers N and M(1<=N,Mm=8) which indicate the size of the labyrinth. Then N lines follow, each line contains M integers. The array indicates the layout of the labyrinth. 
There are five integers which indicate the different type of area in the labyrinth: 
0: The area is a wall, Ignatius should not walk on it. 
1: The area contains nothing, Ignatius can walk on it. 
2: Ignatius' start position, Ignatius starts his escape from this position. 
3: The exit of the labyrinth, Ignatius' target position. 
4: The area contains a Bomb-Reset-Equipment, Ignatius can delay the exploding time by walking to these areas. 

Output

For each test case, if Ignatius can get out of the labyrinth, you should output the minimum time he needs, else you should just output -1. 

Sample Input

3
3 3
2 1 1
1 1 0
1 1 3
4 8
2 1 1 0 1 1 1 0
1 0 4 1 1 0 4 1
1 0 0 0 0 0 0 1
1 1 1 4 1 1 1 3
5 8
1 2 1 1 1 1 1 4 
1 0 0 0 1 0 0 1 
1 4 1 0 1 1 0 1 
1 0 0 0 0 3 0 1 
1 1 4 1 1 1 1 1 

Sample Output

4
-1
13

这个人做了个噩梦,身处迷宫,并且迷宫里有炸弹,要在炸弹爆炸(炸弹定时6分钟)之前走出这个迷宫,一分钟走一步,

看他是被炸死,还是活着走出迷宫,

如果能出去,就输出他必须用来找到迷宫出口的最短时间,

不能就输出 -1 

DFS+剪枝

/*
0 是墙不能走,1可以走,2开始的位置,3出口,4,炸弹装置
*/
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
#define inf 0x3f3f3f3f
int mapp[10][10],n,m,sx,sy,ex,ey,minn,tim[10][10],step[10][10];
int dx[4]={0,1,0,-1};//tim 表示走到 i,j用时多少,step代表 走到i,j步数是多少
int dy[4]={1,0,-1,0};//len时间  cnt步数
void dfs(int x,int y,int len,int cnt)
{
    if(x<0||y<0||x>=n||y>=m)return ;
    if(len<=0||cnt>=minn) return ;
    if(mapp[x][y]==0) return ;
    if(mapp[x][y]==3)
    {
        if(cnt<minn) minn=cnt;
        return ;
    }
    if(mapp[x][y]==4)
    {
        len=6;
    }
    /*从当前点x,y走到下一个可能点的距离大于从其他途径到tx,ty的距离,
且到tx,ty点时的剩余时间大于由x,y点到tx,ty点后的剩余时间,就跳过.
(从其他路径到tx,ty有更短的距离和更短的时间那这个点接下去就不用遍历了,因为最优解不可能出现在这条路径上,所以提前剪掉)*/
    if(cnt>=step[x][y]&&tim[x][y]>=len) return ;
    step[x][y]=cnt;
    tim[x][y]=len;
    for(int i=0;i<4;i++)
    {
        int tx=x+dx[i];
        int ty=y+dy[i];
        dfs(tx,ty,len-1,cnt+1);
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        memset(tim,0,sizeof(tim));
        memset(step,inf,sizeof(step));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                cin>>mapp[i][j];
                if(mapp[i][j]==2)
                {
                    sx=i;
                    sy=j;
                }
                else if(mapp[i][j]==3)
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        int len=6;
        int cnt=0;
        minn=inf;
        dfs(sx,sy,len,cnt);
        if(minn==inf )
            cout<<"-1"<<endl;
        else cout<<minn<<endl;
    }return 0;
}

BFS 

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
#define inf 0x3f3f3f3f
int mapp[10][10],n,m;
int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
struct node
{
    int x,y;
    int step,time;//记录步数和时间
}s;
void bfs()
{
    queue<node > q;//队列实现
    node q1,q2;//交换值,相当于temp;
    q.push(s);
    //队列为空时 说明 已经扫描到结果或者完全扫描结束(还没找到结果)
    while(!q.empty())
    {
        q1=q.front();//将队头的数据拿出来
        q.pop();//将队头弹出
        //开始上下左右搜
        for(int i=0;i<4;i++)
        {
            q2.x=q1.x+dir[i][0];
            q2.y=q1.y+dir[i][1];
            q2.step=q1.step+1;
            q2.time=q1.time-1;
            if(q2.x>=0&&q2.y>=0&&q2.x<n&&q2.y<m&&mapp[q2.x][q2.y]!=0&&q2.time>0)
            {
                if(mapp[q2.x][q2.y]==3)
                {
                    cout<<q2.step<<endl;//找到结束
                    return ;
                }
                else if(mapp[q2.x][q2.y]==4)
                {
                    q2.time=6;
                    mapp[q2.x][q2.y]=0;//标记已经走过
                } q.push(q2);
            }

        }

    }cout<<"-1"<<endl;
    return ;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                cin>>mapp[i][j];
                if(mapp[i][j]==2)
                {
                    s.x=i;
                    s.y=j;
                    s.time=6;
                    s.step=0;
                }
            }
        }
        bfs();
    }return 0;
}

 

### HDU 1072 C++ 实现解析 HDU 1072 是一个经典的动态规划问题,题目名称为 **Catch That Cow**。该问题的核心在于通过广度优先搜索 (BFS) 来寻找从起点到终点的最短路径步数。 #### 题目描述 给定两个整数 `K` 和 `N`,表示农夫的位置和奶牛的目标位置。农夫可以通过三种方式移动: - 走一步到达 `K + 1` - 走一步到达 `K - 1` - 瞬间传送到 `2 * K` 目标是最少经过多少次操作才能让农夫追上奶牛。 --- #### 解决方案概述 此问题可以建模为图上的 BFS 搜索问题。为了防止重复访问某些节点并优化性能,通常会引入一个标记数组来记录已经访问过的状态。以下是解决方案的关键点: - 使用队列存储当前的状态 `(position, steps)`,其中 `position` 表示当前位置,而 `steps` 则是从起始点出发所花费的操作次数。 - 对于每一个可能的动作(即走一步或瞬间传送),将其加入队列以便后续处理[^1]。 - 如果某个动作超出了合理范围或者已经被访问过,则跳过它以减少不必要的计算开销[^2]。 下面提供了一个完整的C++程序实现这一逻辑: ```cpp #include <bits/stdc++.h> using namespace std; const int MAX_POS = 1e5; // 定义最大可达到的位置 int visited[MAX_POS + 1]; void bfs(int start, int end){ queue<pair<int,int>> q; memset(visited,-1,sizeof(visited)); q.push({start,0}); visited[start]=0; while(!q.empty()){ pair<int,int> current=q.front();q.pop(); if(current.first==end){cout<<current.second<<endl;return;} vector<int> next_positions={current.first*2,current.first+1,current.first-1}; for(auto &next_pos : next_positions){ if(next_pos>=0 && next_pos<=MAX_POS && visited[next_pos]==-1){ visited[next_pos]=current.second+1; q.push({next_pos,visited[next_pos]}); } } } } int main(){ ios::sync_with_stdio(false); cin.tie(NULL); int N,K; cin >> N >> K; bfs(N,K); } ``` 上述代码实现了基于BFS算法求解最小步数的功能,并考虑到了边界条件以及效率优化措施[^3]。 --- #### 关键技术细节说明 - **初始化**: 将所有位置设置成未被访问(-1),仅当某位置第一次被发现时才更新其对应的最少步骤数。 - **终止条件**: 当前探索的位置正好等于目标位置时立即停止搜索并输出结果。 - **剪枝策略**: 只有那些尚未访问且处于合法区间内的新位置才会被列入待考察列表之中[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值