PAT 1091.Acute Stroke

本文介绍了一种基于三维空间的广度优先搜索(BFS)算法实现,该算法用于在一个三维矩阵中寻找连通区域,并统计特定条件下连通区域内的像素数量。通过对每个像素点进行判断,确保遍历过程中只访问符合条件的相邻像素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一道比较简单的30分的题目,经典的bfs,skr。

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <cstdio>
#include <map>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

struct node{
    int x,y,z;
}Node;

int n,m,slice,t;
int pixel[1290][130][61];
int inq[1290][130][61] = {0};
int xx[6] = {0,0,0,0,1,-1};
int yy[6] = {0,0,1,-1,0,0};
int zz[6] = {1,-1,0,0,0,0};

int judge(int x,int y,int z)
{
    if(x>=n||x<0||y>=m||y<0||z>=slice||z<0)
        return 0;
    if(pixel[x][y][z]==0||inq[x][y][z]==1)
        return 0;
    return 1;
}

int bfs(int x,int y,int z)
{
    int tot=0;
    queue<node> Q;
    Node.x=x,Node.y=y,Node.z=z;
    Q.push(Node);
    inq[x][y][z]=1;
    while(!Q.empty())
    {
        node top=Q.front();
        Q.pop();
        tot++;

        for(int i=0;i<6;i++)
        {
            if(judge(top.x+xx[i],top.y+yy[i],top.z+zz[i])==1)
            {
                Node.x=top.x+xx[i];
                Node.y=top.y+yy[i];
                Node.z=top.z+zz[i];
                Q.push(Node);
                inq[top.x+xx[i]][top.y+yy[i]][top.z+zz[i]]=1;
            }

        }
    }
    if(tot >= t)
        return tot;
    else
        return 0;
}

int main()
{
    scanf("%d%d%d%d",&n,&m,&slice,&t);
    for(int z=0;z<slice;z++){
        for(int x =0;x<n;x++){
            for(int y=0;y<m;y++)
                scanf("%d",&pixel[x][y][z]);
        }
    }
    int ans=0;
    for(int z=0;z<slice;z++){
        for(int x=0;x<n;x++){
            for(int y=0;y<m;y++){
                if(pixel[x][y][z]==1&&inq[x][y][z]==false)
                    ans += bfs(x,y,z);
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值