1091. Acute Stroke (30) -- DFS(三维空间)

题目地址:http://www.patest.cn/contests/pat-a-practise/1091

这题题目理解很关键,就是个三维空间,每一个点的相邻点有6个,下面是参考网上的代码写出来的 可以ac

// http://www.patest.cn/contests/pat-a-practise/1091
// 1091. Acute Stroke (30)

#include <stdio.h>
#include <iostream> 
#include <stdlib.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <map>
#include <unordered_map>
#include <queue>
#include <vector>
#include <set>
#include <iterator>

using namespace std;

#define M 1287
#define N 129
#define L 61

int m,n; // m*n matrix
int l; //L (<=60) is the number of slices of a brain
int t; // T is the integer threshold (i.e. if the volume of a connected core is less than T, then that core must not be counted

/* where 1 represents a pixel of stroke,and 0 means normal */

int a[L][M][N];

struct poin{
    int z, x, y;
    poin(int _z, int _x, int _y)
    {
        z = _z;
        x = _x;
        y = _y;
    }
};


// 6个相邻点

int volumn ;
int totalVolume;

void dfs(int k, int i, int j)
{
    if (a[k][i][j] == 0) // 起点都是 0 可以退出了
        return;
    queue<poin> p;
    p.push(poin(k,i,j));
    while (!p.empty())
    {
        poin nowP = p.front();
        p.pop();
        int z = nowP.z;
        int x = nowP.x;
        int y = nowP.y;
        if (a[z][x][y] == 1)
        {
            a[z][x][y] = 0; // 需要将其置为0,这个不能没有
            volumn++;
            if (z > 0) 
                p.push(poin(z - 1, x, y)); //下
            if (z + 1 < l) 
                p.push(poin(z + 1, x, y)); // 上
            if (x > 0)
                p.push(poin(z, x - 1, y)); // 左
            if (x + 1 < m)
                p.push(poin(z, x + 1, y));// 右
            if (y > 0)
                p.push(poin(z, x, y - 1)); // 前
            if (y + 1 < n)
                p.push(poin(z, x, y + 1)); // 后
        }
    }
}

int main()
{
    //freopen("in", "r", stdin);
    scanf("%d%d%d%d", &m, &n, &l, &t);
    int i, j, k;

    for (k = 0; k < l; k++) // l 个
    {
        for (i = 0; i < m; i++) //一个 slice
        {
            for (j = 0; j < n; j++)
            {
                scanf("%d", &a[k][i][j]);
            }
        }
    }

    totalVolume = 0;

    for (k = 0; k < l; k++) // l 个
    {
        for (i = 0; i < m; i++) //一个 slice
        {
            for (j = 0; j < n; j++)
            {
                volumn = 0;
                dfs(k, i, j);
                if (volumn >= t)
                    totalVolume += volumn;
            }
        }
    }

    printf("%d\n",totalVolume);
    return 0;
}

你可能感兴趣的:(DFS)