A1091 Acute Stroke (30) BFS

本文介绍了一种在三维矩阵中使用广度优先搜索(BFS)算法进行遍历的方法,详细展示了如何通过BFS算法在三维空间中寻找连通区域,并计算其连通性。该算法首先初始化矩阵和辅助数据结构,然后从指定起点开始,利用队列进行逐层遍历,最终统计可达节点数量。

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

#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=130;
int  n,m,l,num,matrix[maxn][maxn][maxn]={0};
int X[6]={0,0,1,-1,0,0};
int Y[6]={1,-1,0,0,0,0};
int Z[6]={0,0,0,0,1,-1};
bool inq[maxn][maxn][maxn]={false};
struct node
{
	int x, y,z;
};
bool test(int x,int y ,int z)
{
	if(x>=m||x<0||y>=n||y<0||z>=l||z<0)return false;
	else if(inq[x][y][z]==true||matrix[x][y][z]==0)return false;
	else return true;
}
int BFS(int x,int y,int z)
{
    queue<node> q;
    int tn=1;
    node temp;
    temp.x=x,temp.y=y,temp.z=z;
    q.push(temp);
    inq[x][y][z]=true;
    while(!q.empty())
    {
    	node top=q.front();
    	q.pop();
    	for (int i=0;i<6;i++)
    	{
    		int newX=top.x+X[i];
    	    int newZ=top.z+Z[i];
    	    int newY=top.y+Y[i];
    	    if(test(newX,newY,newZ))
    	    {
    	    	temp.x=newX;
    	    	temp.y=newY;
    	    	temp.z=newZ;
				q.push(temp);
				inq[newX][newY][newZ]=true;
				tn++;
			}
		}
	}
	if(tn>=num)
	return tn;
	else 
	return 0;
}
int main()
{
   cin>>m>>n>>l>>num;
   for(int k=0;k<l;k++)
   {
   	for (int i=0;i<m;i++)
   	{
   		for(int j=0;j<n;j++)
   		{
   			scanf("%d",&matrix[i][j][k]);
		   }
	   }
   }
   int ans=0;
    for(int k=0;k<l;k++)
   {
   	for (int i=0;i<m;i++)
   	{
   		for(int j=0;j<n;j++)
   		{
   			if(matrix[i][j][k]==1&&inq[i][j][k]==false)
   			{
   				ans+=BFS(i,j,k);
			   }
		   }
	   }
   }
   printf("%d",ans); 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值