【题意】一个立方体迷宫,a,b,c为其长宽高,输入每个坐标的状态,0表示路,1表示墙。一个人从(0,0,0)位置出发,往相邻6个方位走一步会花1分钟,问该人能否在t分钟内走出迷宫,不能的话输出-1,能的话输出时间
【思路】用队列实现广度优先搜索
【限制】当遍历的到点在场外/是墙/已经过时,直接跳过不作处理
【输入输出】
输入:
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
输出:
11
#include<iostream>
#include<cstring>
#include<vector>
#include<math.h>
#include<algorithm>
#include<queue>
using namespace std;
#define maxi 0x3f3f3f3f
int cube[51][51][51];
int mark[51][51][51];
struct e
{
int x,y,z,t;
};
queue<e> Q;
int g[6][3]={
0,1,0,
0,-1,0,
0,0,1,
0,0,-1,
1,0,0,
-1,0,0
};
int main(int argc, char const *argv[])
{
int n,a,b,c,t;
cin>>n;
while(n--)
{
cin>>a>>b>>c>>t;
memset(mark,false,sizeof(mark));
for(int i=0;i<a;i++)
{
for (int j = 0; j < b; ++j)
{
{
for(int k=0;k<c;k++)
cin>>cube[i][j][k];
/* code */
}
}
}
e nexp;
nexp.x=0;
nexp.y=0;
nexp.z=0;
nexp.t=0;
mark[0][0][0]=true;//一开始忘记加了
Q.push(nexp);
bool flag=true;
while(!Q.empty())
{
e now=Q.front();
Q.pop();
int nx,ny,nz;
for(int i=0;i<6;i++)
{
nx=now.x+g[i][0];
ny=now.y+g[i][1];
nz=now.z+g[i][2];
if(nx<0||nx>=a||ny<0||ny>=b||nz<0||nz>=c||cube[nx][ny][nz]==1||mark[nx][ny][nz]==true)//不是nx<=0!!是可以==0的
continue;
e tmp;
tmp.x=nx;tmp.y=ny;tmp.z=nz;
tmp.t=now.t+1;
Q.push(tmp);
mark[nx][ny][nz]=true;//忘记mark它为经过了!!
if(nx==a-1&&ny==b-1&&nz==c-1)
{
if(tmp.t<=t)
{
cout<<tmp.t<<endl;
flag=false;
break;
}
}
}
if(!flag)break;
}
if(flag)
cout<<-1<<endl;
while(!Q.empty())Q.pop();//别忘了清空队列!!!!
}
return 0;
}