来源:点击打开链接
三维BFS,比起二维BFS来说多了一维,但是也没什么难度。
第一次卡时间过,在大神的指导下明白了,还可以进行优化。
1、搜索方向变成了6个。
2、需要考虑到出口处为墙的情况。
3、如果有这个会大大提高效率:if(a+b+c-3>tarstep) {printf("-1\n");continue;}(起点与终点间最短路径大于时间限度)
CODE:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int dir[6][3]= {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
int a,b,c,tarstep;
int mat[60][60][60];
int visited[60][60][60];
class node
{
public:
int x;
int y;
int z;
int step;
};
node s1,e1;
int judge(int x,int y,int z)
{
if(x>=0 && x<a && y>=0 && y<b && z>=0 && z<c && mat[x][y][z]==0 && visited[x][y][z]==0)
return 1;
else
return 0;
}
int bfs(node st,node ed)
{
if(mat[ed.x][ed.y][ed.z]==1)//特判1
return -1;
if(a+b+c-3>tarstep) //特判2
{
return -1;
}
memset(visited,0,sizeof(visited));
queue<node> q;
node first,next;
first.x=st.x;
first.y=st.y;
first.z=st.z;
first.step=0;
visited[first.x][first.y][first.z]=1;
q.push(first);
while(!q.empty())
{
first=q.front();
q.pop();
for(int i=0; i<6; i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
next.z=first.z+dir[i][2];
next.step=first.step+1;
if(next.x==ed.x && next.y==ed.y && next.z==ed.z && next.step<=tarstep)
return next.step;
if(judge(next.x,next.y,next.z))
{
visited[next.x][next.y][next.z]=1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int testcase;
scanf("%d",&testcase);
while(testcase--)
{
scanf("%d%d%d%d",&a,&b,&c,&tarstep);
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
for(int k=0;k<c;k++)
{
scanf("%d",&mat[i][j][k]);
}
}
}
s1.x=0;
s1.y=0;
s1.z=0;
s1.step=0;
e1.x=a-1;
e1.y=b-1;
e1.z=c-1;
e1.step=0;
int res=bfs(s1,e1);
printf("%d\n",res);
}
return 0;
}