搜索法 | 1091bfs搜索:三维bfs

首先我们来理解样例输入:

尺寸:3行4列5片   阈值:2

1 1 1 1
1 1 1 1
1 1 1 1
-------
0 0 1 1
0 0 1 1
0 0 1 1
-------
1 0 1 1
0 1 0 0
0 0 0 0
-------
1 0 1 1
0 0 0 0
0 0 0 0
-------
0 0 0 1
0 0 0 1
1 0 0 0

样例中,一共有三块连通区域,分别是红色,蓝色,紫色。因为紫色的元素数小于2,所以不考虑。ans=26

编码过程中出现了很多bug,主要问题出在bfs结构的编写上。编写bfs结构一定要牢记“出队标记入队标记入队判断”这三个编写要点,就能保证AC。

代码:

#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>


#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 1010
#define MAX 0x06FFFFFF
#define V vector<int>

using namespace std;

int g[100][2000][200];
int vis[100][2000][200];
int n,m,T,l,cnt;

typedef struct pt{
    int x,y,z;
    pt(int z=0,int x=0,int y=0):x(x),y(y),z(z){    //注意第一个是组号 
    }
};

void pushIn(int z,int x,int y,queue<pt> &q) {
    if(z<l && z>=0 && x<m && x>=0 && y<n && y>=0 && g[z][x][y] && !vis[z][x][y]){
        q.push(pt(z,x,y));
        vis[z][x][y]=1;
        cnt++;
    }
}

int main(){
//    freopen("I:\pat\图的遍历\1091.txt","r",stdin);
    int a,b,i,j,k;//行 列 组 阈值 
    I("%d%d%d%d",&m,&n,&l,&T);
    FF(i,l)FF(j,m)FF(k,n){
        I("%d",&g[i][j][k]);//组 行 列 
    }
    int ans=0;
    FF(i,l)FF(j,m)FF(k,n) if(g[i][j][k] && !vis[i][j][k]){
        queue<pt>     q;
        q.push(pt(i,j,k));
        cnt=1; 
        while(!q.empty()){
            pt t=q.front();
            q.pop();
            int tx=t.x,ty=t.y,tz=t.z;
            vis[tz][tx][ty]=1;
            //6个方向 
            pushIn(tz+1,tx,ty,q);
            pushIn(tz-1,tx,ty,q);
            pushIn(tz,tx+1,ty,q);
            pushIn(tz,tx-1,ty,q);
            pushIn(tz,tx,ty+1,q);
            pushIn(tz,tx,ty-1,q);
        }
        if(cnt>=T){
            ans+=cnt;
        }
    }
    O("%d",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/TQCAI/p/8528197.html