示例1
输入
2 .* .. *. ..
输出
4
题意:中文题,不过多叙述题意。
思路:这道题的话,和二维BFS走迷宫差不多,不过现在是三维BFS。既然是三维BFS,那么方向向量的写法为
int dx[]={0,1,0,-1,0,0};
int dy[]={1,0,-1,0,0,0};
int dz[]={0,0,0,0,1,-1};
然后我们再套用模板即可。
AC代码:
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
typedef long long ll;
const int maxx=110;
const int mod=10007;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
using namespace std;
char a[maxx][maxx][maxx];
int dx[]= {0,1,0,-1,0,0};
int dy[]= {1,0,-1,0,0,0};
int dz[]= {0,0,0,0,1,-1};
typedef struct node
{
int x;
int y;
int z;
} edge;
queue<edge>q;
int dis[maxx][maxx][maxx];
int n;
int bfs()
{
memset(dis,-1,sizeof(dis));
q.push({1,1,1});
dis[1][1][1]=1;
while(!q.empty())
{
edge u=q.front();
q.pop();
for(int i=0; i<6; i++)
{
int x=u.x+dx[i];
int y=u.y+dy[i];
int z=u.z+dz[i];
if(x>=1 && y>=1 && z>=1 && x<=n && y<=n && z<=n && dis[x][y][z]==-1 && a[x][y][z]!='*')
{
dis[x][y][z]=dis[u.x][u.y][u.z]+1;
q.push({x,y,z});
}
}
}
return dis[n][n][n];
}
int main()
{
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
for(int k=1; k<=n; k++)
{
cin>>a[i][j][k];
}
}
}
if(a[n][n][n]=='*')
{
printf("-1\n");
return 0;
}
int ans=bfs();
printf("%d\n",ans);
return 0;
}