广度优先搜索遍历之数块数(算法笔记学习)

/*给出一个m*n的矩阵,矩阵中的元素或为0,或为1.称位置(x,y)与其上下左右四个位置(x,y+1);(x,y-1)(x+1,y)(x-1,y)是相邻的。如果矩阵
中有若干各个1是相邻的(不必两两相连),那么称这些1构成了一个块。求给定的矩阵中块的个数。
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
例如上个6*7矩阵中的“块”的个数为4;*/
#include<stdio.h>
#include<queue>
using namespace std;
const int maxn=100;
struct node{
int x,y;
}Node;
int m,n;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
bool judge(int x,int y)
{
if(x>=n||x<0||y>=m||y<0) return false;
if(matrix[x][y]==0||inq[x][y]==true) return false;
return true;
}
void BFS(int x,int y){
	queue<node>Q;
	Node.x=x;Node.y=y;
	Q.push(Node);
	inq[x][y]=true;
	while(!Q.empty()){
		node top=Q.front();
		Q.pop();
		for(int i=0;i<4;i++)
		{
			int newx=top.x+X[i];
			int newy=top.y+Y[i];
			if(judge(newx,newy))
			{
				Node.x=newx;
				Node.y=newy;
				Q.push(Node);
				inq[newx][newy]=true; 
			}
		}
	}
	}
	int main()
	{
		scanf("%d%d",&n,&m);
		for(int x=0;x<n;x++)
		{
			for(int y=0;y<m;y++)
			{
				scanf("%d",&matrix[x][y]);
			}
		}
		int ans=0;
		for(int x=0;x<n;x++){
			for(int y=0;y<m;y++)
			{
				if(matrix[x][y]==1&&inq[x][y]==false){
					ans++;
					BFS(x,y);
				}
			}
		}
		printf("%d\n",ans);
		return 0;
	}
/*	另附广搜模板: 
void BFS(int s){
queue<int> q;
q,push(s);
while(!q.empty()){
取出队首元素;
访问队首元素;
将队首元素出队;
将TOP节点的下层未入队节点入队, 并设置为已经入队
*/ 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值