天梯赛L3 004 - 肿瘤诊断 ( 三维BFS )

L3 004

思路

这里要注意的是L层切片是叠放的, 上下也联通, 所以应当看作是三维的搜索BFS
判断连通块的话基本就是清楚标记就ok, 遍历到之后直接令g[z][x][y] = 0;
参考链接: 【经典/基础BFS+略微复杂的题意】PAT-L3-004. 肿瘤诊断

至于用BFS还是DFS的问题呢, 听说DFS这道题会因为递归层数太深爆栈, 先记一下, 等理解了再回来补, 也希望有dalao能不吝赐教

AC代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
#define mst(a) memset(a, 0, sizeof(a))
using namespace std;

int m, n, l, t, num;
int g[65][1300][130];
int dz[] = {1,-1,0,0,0,0};
int dx[] = {0,0,1,-1,0,0};
int dy[] = {0,0,0,0,1,-1};

struct tumor{
    int z, x, y;
};

bool ir( int point, int mmax ){
    if( point >= 0 && point < mmax )
        return true;
    return false;
}

bool judge( int z, int x, int y )
{
    if( ir(z,l) && ir(x,m) && ir(y,n) && g[z][x][y] == 1 )
        return true;
    return false;
}

int bfs( int z, int x, int y )
{
    int num = 1;
    queue<tumor> Q;
    tumor tt;
    tt.z = z, tt.x = x, tt.y = y;
    Q.push(tt);
    g[z][x][y] = 0;
    while( !Q.empty() ){
        tumor p = Q.front();
        Q.pop();
        for( int i = 0; i < 6; i++ ){
            int zz = p.z+dz[i], xx = p.x+dx[i], yy = p.y+dy[i];
            if( judge( zz, xx, yy ) ){
                g[zz][xx][yy] = 0;
                num++;
                tt.z = zz, tt.x = xx, tt.y = yy;
                Q.push(tt);
            }
        }
    }
    //cout << num << endl;
    return num >= t ? num : 0;
}

int main()
{
    scanf("%d%d%d%d",&m,&n,&l,&t);
    int sum = 0;
    for( int k = 0; k < l; k++ )
        for( int i = 0; i < m; i++ )
            for( int j = 0; j < n; j++ )
                scanf("%d",&g[k][i][j]);
    for( int k = 0; k < l; k++ )
        for( int i = 0; i < m; i++ )
            for( int j = 0; j < n; j++ )
                if( g[k][i][j] )
                    sum += bfs( k, i, j );
    printf("%d\n",sum);
    return 0;
}
posted @ 2018-03-21 20:59  JinxiSui  阅读(256)  评论(0编辑  收藏  举报