hdu 1072

本文介绍了一个使用广度优先搜索(BFS)解决迷宫问题的示例程序。该程序允许地图上的点被重复访问,并特别关注数值为4的点,这些点会重新设置搜索的时间限制。通过一个具体的实现案例,展示了如何进行节点探索、状态记录及路径查找。

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

因为0<=n,m<=8的,所以广搜是没有问题的,题目规定每个点可以重复走,只需要将数值为4的点标记就可以了.

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
const int maxn = 10;
using namespace std;
struct node{
   int x,y;
   int time;
   int ans;
};
int dir[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int map[maxn][maxn];
int vis[maxn][maxn];
int x1,y1;
int row,col;
int dfs(){
     queue<node> que;
     node t;
     memset(vis,false,sizeof(vis));
     t.time = 6;
     t.ans = 0;
     t.x = x1 , t.y = y1;
     que.push(t);
     while(!que.empty()){
         t = que.front();
         que.pop();
         node temp = t;
         if(map[temp.x][temp.y] == 3  && temp.time > 0)
            return temp.ans;
         for(int i = 0; i < 4; ++i){
             temp.x = t.x + dir[i][0];
             temp.y = t.y + dir[i][1];
             temp.time = t.time - 1;
             if(temp.x>0 && temp.x<=row && temp.y>0 && temp.y<=col && map[temp.x][temp.y] && !vis[temp.x][temp.y] && temp.time){
                  temp.ans = t.ans + 1;
                  if(map[temp.x][temp.y] == 4 ){
                      temp.time = 6;
                    vis[temp.x][temp.y] = true;
                  }
                  que.push(temp);
             }
         }
     }
     return -1;
}
int main()
{
    int cas;
    scanf("%d",&cas);
    while(cas--){
        scanf("%d %d",&row,&col);
        for(int i = 1; i <= row; ++i)
         for(int j = 1; j <= col; ++j){
               scanf("%d",&map[i][j]);
               if(map[i][j] == 2)
                    x1 = i , y1 = j;
         }
         int ans;
         if((ans = dfs()) != -1)
           printf("%d\n",ans);
         else
           printf("-1\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值