Jelly(三维bfs)

牛客小白月赛 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值