算法笔记8.2 BFS,计算矩阵的块数

问题:求一个矩阵的的块数

1101		//这矩阵块数是3
0100
0011

1.小技巧,增量数组X[],Y[],可以用来表示增加上下左右的位置,命名要注意
2.BFS()是将一个位置周围都是1的数都加入队列,避免重复访问
3.数组下标从0开始,故要注意越界的情况

#include <cstdio>
#include <queue>
 
using namespace std;

const int maxn = 20;
int n,m;	//n*m数组	
int matrix[maxn][maxn] ; 
bool inq[maxn][maxn] = {false};		//是否进入过队列 
int X[4] = {0,1,0,-1};		//命名要大写,不要与x混淆 
int Y[4] = {1,0,-1,0};

struct node{		//位置节点 
	int x,y;
}Node;
 
bool judge(int x, int y){		 
	 
	if(x<0||y<0|| x>=n|| y>=m) return false;	//位置越界则不访问 
	
	//矩阵值为0或者已经在队列了,也不访问 
	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.top() 
		Q.pop();
		for(int i=0; i<4; i++){		//循环4次,得到4个相邻位置 
			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);		//n*m矩阵 
	for(int x=0; x<n; x++){
		for(int y=0; y<m; y++){
			scanf("%d" , &matrix[x][y]);		//初始化矩阵 
		}
	}
	
	int block_n = 0;
	
	for(int x=0; x<n; x++){
		for(int y=0; y<m; y++){
			if(matrix[x][y] == 1 && inq[x][y] == false){		//为1,且不在队列中,记块数+1 
				block_n++;
				BFS(x,y);		//找出相邻的所有1,并将其入队列 
				
			} 
		}
	} 

	printf("%d",block_n);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值