BFS——矩阵中“相邻”元素的个数

版权声明:关中大侠Lv轻侯 https://blog.csdn.net/weixin_44312186/article/details/88734929

问题概述:

         给出一个N×M矩阵,对于矩阵元素(x,y)称其上下左右四个位置(x,y+1),(x,y-1),(x+1,y),(x-1,y)是“相邻”的。如果一个矩阵的元素中只有0,1,若有若干个1是相邻的,则这些1就构成了一个“块”,求矩阵中块的个数。

例如:6×7矩阵中,块的个数为4

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

代码:

#include<cstdio>
#include<queue>
using namespace std;
const int maxn=100;
struct node{
	int x,y;
}NODE;

int n,m;//矩阵大小为n ×m 
int martix[maxn][maxn];//01矩阵 
bool inq[maxn][maxn]={false}; //判断是否进入过队列 
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};//注意x和y的对应关系 

bool judge(int x,int y){//判断[x][y]是否需要访问 
	if(x>=n||x<0||y>=m||y<0) return false;
	if(martix[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",&martix[x][y]);
		}
	}
	int ans=0;
	for(int x=0;x<n;x++){
		for(int y=0;y<m;y++){
			if(martix[x][y]==1&&inq[x][y]==false){
				ans++;
				BFS(x,y);
			} 
		}
	}
	printf("%d",ans);
	return 0;
}

ps:BFS基于队列实现,且按照层次的顺序从上到下,基本写法:

void BFS(int s)//s为队列的队首元素
{
    queue<int> q;
    q.push(s);
    while(!q.empty()){
        ....;     //取出队首元素top
        ....;     //访问队首元素top(如进行输出,打印等等操作)
        q.pop();  //将队首元素出队
        ....;     //将top元素的下一层结点中未曾入队的结点全部入队
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_44312186/article/details/88734929
今日推荐