BFS判定矩阵中的块数

在这里插入图片描述输入:
6 7
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
输出:
4
vector存储版

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int maxn=30,maxm=30;
bool s[maxn][maxm]={false};
int m,n;
queue<int>qh,ql;
void BFS(vector<int> *v,int x,int y){	
	qh.push(x);ql.push(y);
	s[x][y]=true;
	while(!ql.empty()){
		int nx=qh.front(),ny=ql.front();
		qh.pop();ql.pop();
		for(int i=-1;i<2;i++)
			for(int j=-1;j<2;j++){
				if(abs(i)!=abs(j)&&nx+i>=0&&ny+j>=0&&nx+i<m&&ny+j<n&&!s[nx+i][ny+j]&&v[nx+i][ny+j]!=0){
					qh.push(nx+i);ql.push(ny+j);
					s[nx+i][ny+j]=true;
				}
				
			}
	}
}
int main(){
	int ans=0,tem;
	cin>>m>>n;
	vector<int>v[m];	
	for(int i=0;i<m;i++)
		for(int j=0;j<n;j++){
		cin>>tem;
		v[i].push_back(tem);
	}
	for(int i=0;i<m;i++){
		for(int j=0;j<n;j++){
			if(v[i][j]!=0&&!s[i][j]){
				ans++;
				BFS(v,i,j);
			}
			
		}
	}
cout<<ans;
	return 0;
} 


算法笔记上的版本

#include<iostream>
#include<queue>
using namespace std;
struct node{
	int x,y;
}Node;
const int maxn=100;
int n,m;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};
int X[4]={0,0,1,-1},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(){
	cin>>n>>m;
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			cin>>matrix[i][j]; 
		}
	}
	int ans=0;
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			if(matrix[i][j]==1&&inq[i][j]==false){
				ans++;
				BFS(i,j);
			}
		}
	}
	cout<<ans;
	return 0;
}

注:是上下左右四个位置而不是九个位置,在使用队列时,我错误的在while循环中使用递归,这是思想没有明确的原因,没有明确在BFS函数中到底要完成什么,BFS函数是为了完成一个块的判定而非一个个点的判定,在main函数中的for循环才是点的判断

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值