A-Jelly(牛客算法週週練3)(三維BFS)

示例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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章