1. 程式人生 > >GPLT L3-004. 腫瘤診斷【三維bfs求連通塊】

GPLT L3-004. 腫瘤診斷【三維bfs求連通塊】

題目:腫瘤診斷

題意:找三維圖中的連通塊的面積,即1的個數   連通塊有個要求如果小於給定的範圍就不計!

思路:開始時用dfs做,棧溢位了。。。資料大了!

換成bfs尋找連通即可!

程式碼:

#include <stdio.h>
#include <cstring>
#include <queue>
using namespace std;
const int row = 1500;
const int col = 200;
const int heg = 100;
const int dirx[] = {1,-1,0,0,0,0};
const int diry[] = {0,0,-1,1,0,0};
const int dirz[] = {0,0,0,0,1,-1};
int g[heg][row][col];
int n,m,l,t,cnt;
struct node{
    int x,y,z;
    node(int tx,int ty,int tz):x(tx),y(ty),z(tz){};
};
void bfs(int sz,int sx,int sy){
    g[sz][sx][sy] = 0;
    queue<node>Q;
    Q.push(node(sx,sy,sz));
    while(!Q.empty()){
        node pre = Q.front();Q.pop();
        for(int i=0;i<6;i++){
            int tx = pre.x+dirx[i] , ty = pre.y+diry[i] , tz = pre.z + dirz[i];
            if(tx < 0 || tx >= n || ty < 0 || ty >= m || tz < 0 || tz >= l) continue;
            if(g[tz][tx][ty])
            {
                g[tz][tx][ty] = 0;
                Q.push(node(tx,ty,tz));
                cnt++;
            }
        }
    }
    return;
}
int main()
{
    while(~scanf("%d%d%d%d",&n,&m,&l,&t)){
        for(int k=0;k<l;k++)
            for(int i=0;i<n;i++)
                for(int j=0;j<m;j++) scanf("%d",&g[k][i][j]);
        int ans = 0;
        for(int k=0;k<l;k++)
            for(int i=0;i<n;i++)
                for(int j=0;j<m;j++){
                    if(g[k][i][j]){
                        cnt = 1;
                        bfs(k,i,j);
                        if(cnt >= t) ans += cnt;
                    }
                }
        printf("%d\n",ans);
    }
    return 0;}