6.2广度优先搜索

在这里插入图片描述

#include <stdio.h>
#include <queue>
using namespace std;
struct node{//状态结构体 
 int x,y,z;//坐标
 int t;//所需要时间 
};  
queue<node> q;//保存入度为0的节点 
int next[][3]={//前后左右上下六个移动方向 
 1,0,0,
 -1,0,0,
 0,1,0,
 0,-1,0,
 0,0,1,
 0,0,-1
}; 
int maze[50][50][50];//存放坐标信息
bool mark[50][50][50];//标记数组,一旦处理完就标记其位置为true 
int bfs(int a,int b,int c){
 while(!q.empty()){
  node nowp=q.front();//得到队头状态 
  q.pop();//弹出队头
  for(int i=0;i<6;i++){
   int nx=nowp.x+next[i][0];
   int ny=nowp.y+next[i][1];
   int nz=nowp.z+next[i][2];//计算新坐标 
   if(nx<0||nx>=a||ny<0||ny>=b||nz<0||nz>=c) continue;//若新坐标在立方外,跳过 
   if(maze[nx][ny][nz]==1) continue;//该位置是墙,跳过
   if(mark[nx][ny][nz]) continue;//该位置已被标记,跳过
   node tmp;
   tmp.x=nx;
   tmp.y=ny;
   tmp.z=nz;
   tmp.t=nowp.t+1;//将该位置的状态封装成node类
   q.push(tmp);//将该node压入队列
   mark[nx][ny][nz]=true;
   if(nx==a-1&&ny==b-1&&nz==c-1) return tmp.t;//若该坐标为终点,直接返回其耗时 
  } 
 }
 return -1;//所有状态都找完都未找到出口坐标,返回-1 
}
int main(){
 int n;
 scanf("%d",&n);//输入个数 
 while(n--){
  int a,b,c,t;
  scanf("%d%d%d%d",&a,&b,&c,&t);
  for(int i=0;i<a;i++)
   for(int j=0;j<b;j++)
    for(int k=0;k<c;k++){
     scanf("%d",&maze[i][j][k]);
     mark[i][j][k]=false;//初始化城堡数组即标记数组 
          }
  while(!q.empty()) q.pop();//清空队列
  mark[0][0][0]=true;//标记出发节点 
  node tmp;
  tmp.x=tmp.y=tmp.z=tmp.t=0;
  q.push(tmp);//出发节点进栈
  int rec=bfs(a,b,c);
  if(rec<=t&&rec!=-1) printf("%d\n\n",rec);
  else printf("-1\n\n"); 
 } 
 return 0;
}

1
3 3 4 20
0 1 1 1
0 0 1 1
0 1 1 1
1 1 1 1
1 0 0 1
0 1 1 1
0 0 0 0
0 1 1 0
0 1 1 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值