牛客小白月赛 21 J Jelly
算法分析
这题是个三维bfs,其实跟二维差不了多少
代码实现
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<math.h>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1e2+5;
int n;
int dx[6]={0,1,0,-1,0,0};
int dy[6]={0,0,0,0,1,-1};
int dz[6]={1,0,-1,0,0,0};
char map[maxn][maxn][maxn];
int dis[maxn][maxn][maxn];
struct dian
{
int x,y,z;
};
bool pd(int x,int y,int z)
{
if(x>=1&&x<=n&&y>=1&&y<=n&&z>=1&&z<=n&&dis[x][y][z]==0&&map[x][y][z]!='*')
return true;
else
return false;
}
void bfs(int x,int y,int z)
{
queue<dian> q;
memset(dis,0,sizeof(dis));
q.push({x,y,z});
map[x][y][z]='*';
dis[x][y][z]=1;//开始位置有果冻
while(q.size())
{
dian s=q.front();
q.pop();
for(int i=0;i<6;i++)
{
int nx=s.x+dx[i];
int ny=s.y+dy[i];
int nz=s.z+dz[i];
if(pd(nx,ny,nz))
{
dis[nx][ny][nz]=dis[s.x][s.y][s.z]+1;
q.push({nx,ny,nz});
}
}
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
for(int k=1;k<=n;k++)
{
cin>>map[i][j][k];
}
}
}
bfs(1,1,1);
if(dis[n][n][n]!=0)
cout<<dis[n][n][n]<<endl;
else
cout<<-1<<endl;
}