BFS解题思路

广度优先算法常用方法:
由队列进行实现,按照层数顺序进行遍历
模板解释
eg:
m*n的01矩阵,求由1构成的块(上下左右都是1)的数量

解题思路:

  1. 读入矩阵
  2. 遍历矩阵,若该值为1且未入队列,则ans++,把其周围为1 的inq置为1 (使用BFS进行,一定要判断是否需要访问
  3. 输出ans
#include <bits/stdc++.h>
using namespace std;
const int maxn=100;
int n,m;
int matrix[maxn][maxn];
int X[4]={0,0,1,-1};//用for循环进行枚举四个方向
int Y[4]={1,-1,0,0}; 
bool inq[maxn][maxn]={false};//是否入队 
struct node{
	int x,y;
}Node;
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){//访问所在的块,将块中的1 的inq设为true 
		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(){
	cin>>n>>m;
	for(int x=0;x<n;x++){
		for(int y=0;y<m;y++){
			cin>>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);//访问整个块 ,将块中的1的inq设为true 
			}
		}
	}
	cout<<ans;
	return 0;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值