A1091 Acute Stroke (30 分| bfs|广度优先搜索,附详细注释,逻辑分析)

写在前面

  • 思路分析
    • 给定1个三维数组, 0表示正常1表示有肿瘤,肿瘤块大小大于等于t才算作是肿瘤,计算所有满足肿瘤块的大小
    • 实现分析:
      • 三维广度优先搜索
        • XYZ三个数组判断方向,对每1个点广度优先累计肿瘤块大小,如果大于等于t就把结果累加
        • 用visit数组标记当前点有没有被访问过,被访问过的结点不再访问
        • judge判断是否超过边界,或当前结点为0不是肿瘤
  • 初步理解,学习ing

测试用例

  • input:
    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
    output:
    26
    

ac代码

  • #include <cstdio>
    #include <queue>
    using namespace std;
    struct node
    {
        int x, y, z;
    };
    //m,n为二维数组维数
    //slice代表三维数组的高度
    //t代表和的最小值
    int m, n, l, t;
    // 对于1个点,在三维坐标下,有六个方向,所以组合必须有六个,枚举注意方向问题
    int X[6] = {1, 0, 0, -1, 0, 0};
    int Y[6] = {0, 1, 0, 0, -1, 0};
    int Z[6] = {0, 0, 1, 0, 0, -1};
    int arr[1300][130][80];
    bool visit[1300][130][80];
    bool judge(int x, int y, int z)
    {
        // 判断是否超过边界
        if(x < 0 || x >= m || y < 0 || y >= n || z < 0 || z >= l) return false;
        // 当前结点为0不是肿瘤
        if(arr[x][y][z] == 0 || visit[x][y][z] == true) return false;
        return true;
    }
    int bfs(int x, int y, int z)
    {
        int cnt = 0;
        node tmp;
        tmp.x = x, tmp.y = y, tmp.z = z;
    
        queue<node> q;
        q.push(tmp);
        visit[x][y][z] = true;
        while(!q.empty())
        {
            node top = q.front();
            q.pop();
            cnt++;
            // 坐标变化数组,由坐标(x,y,z)扩展得到的新坐标均可扩展
            // (x+go[i][0], y+go[i][1], z+go[i][2])
            // 扩展到 上下左右前后 6个方向
            for(int i = 0; i < 6; i++)
            {
                int tx = top.x + X[i];
                int ty = top.y + Y[i];
                int tz = top.z + Z[i];
                if(judge(tx, ty, tz))
                {
                    visit[tx][ty][tz] = true;
                    tmp.x = tx, tmp.y = ty, tmp.z = tz;
                    q.push(tmp);
                }
            }
        }
        if(cnt >= t)
            return cnt;
        else
            return 0;
    }
    int main()
    {
        scanf("%d %d %d %d", &m, &n, &l, &t);
        for(int i = 0; i < l; i++)
            for(int j = 0; j < m; j++)
                for(int k = 0; k < n; k++)
                    scanf("%d", &arr[j][k][i]);
        int ans = 0;
        for(int i = 0; i < l; i++)
        {
            for(int j = 0; j < m; j++)
            {
                for(int k = 0; k < n; k++)
                {
                    if(arr[j][k][i] == 1 && visit[j][k][i] == false)
                        ans += bfs(j, k, i);
                }
            }
        }
        printf("%d", ans);
        return 0;
    }
    
发布了328 篇原创文章 · 获赞 107 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/qq_24452475/article/details/100619225