BFS例题1-01矩阵中块的个数

该博客介绍了如何通过广度优先搜索(BFS)算法解决一个计算机科学中的问题:在一个n*m的01矩阵中,计算所有由上下左右相邻的1组成的块的数量。程序首先读取矩阵的大小和元素,然后利用BFS遍历矩阵,标记已访问的位置,最终输出块的总数。
摘要由CSDN通过智能技术生成
/*
	n*m的01矩阵上下左右相邻的1构成一个块,求块的个数 
*/
#include<cstdio>
#include<queue>

using namespace std;
const int maxn = 100;
struct node{
	int x, y;	//位置(x, y) 
}Node; 

int n, m;	//矩阵大小n*m
int matrix[maxn][maxn]; 	//01矩阵 
bool inq[maxn][maxn] = {false};	//记录位置(x, y)是否已入过队 
int X[4] = {0, 0, 1, -1};	//增量数组 
int Y[4] = {1, -1, 0, 0};

bool judge(int x, int y){	//判断坐标(x, 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值