BFS迷宫求块问题

题目描述:
给出一个m*n的矩阵,矩阵中的元素为0或1.称位置(x,y)与其上下左右四个位置是相邻的。如果矩阵中有若干个1相邻,则称这些1构成了一个块。求给定矩阵中的块数。
输入:

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

#include <iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=100;
struct node{
	int 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是否需要访问 
 	//越界返回false
	 if(x>=n||x<0||y>=m||y<0) return false;
	 //当前位置为0,或x,y移入过队,返回false
	 if(matrix[x][y]==0||inq[x][y]==true)return false;
	 //以上都不满足
	 return true; 
 }
 
 //BFS函数访问位置x,y所在块,将该块所有1的inq都设置为true;
 void BFS(int x,int y){
 	Node.x=x;
 	Node.y=y;//当前节点的坐标为x,y;
 	queue<node>Q;
 	Q.push(Node);//将结点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;//设置位置newx,newy已入过队 
			 }
		 } 
	 } 
	  
 } 
 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]);//读入01矩阵 
		 }
	 }
	 
	 int ans=0;//存放块数
	 for(int x=0;x<n;x++){
	 	for(int y=0;y<m;y++){
	 		//如果元素为1,且未入过队
			 if(matrix[x][y]==1&&inq[x][y]==false){
			 	ans++;
			 	BFS(x,y);
			 } 
		 }
	 } 
	 printf("%d\n",ans);
	 return 0; 
 } 


猜你喜欢

转载自blog.csdn.net/weixin_41988545/article/details/80633741