DFS与BFS的应用

1 篇文章 0 订阅
1 篇文章 0 订阅

<题目>:
给出一个n*m矩阵,矩阵中的元素为0或1,称位置(x,y)与其上下左右四个位置(x,y+1)(x,y-1),(x-1,y),(x+1,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

先用DFS的递归算法实现一下!

/!!!!!我写出来啦! 

#include<cstdio>
#include<queue>
using namespace std;
struct node{
	int x,y;
}Node;
const int maxn = 100;
int n,m,matrix[maxn][maxn];//大小为n*m矩阵 
bool inq[maxn][maxn]={false};
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
//判断是否需要访问,矩阵下标从0开始 
bool judge(int x,int y){
	if(x>=n||x<0||y>=m||y<0)return false;
	if(inq[x][y]==true||matrix[x][y]==0)return false;
	return true;
}
void DFS(int x,int y){
	inq[x][y]=true;
	for(int i=0;i<4;i++){
		int newX=x+X[i];
		int newY=y+Y[i];
		if(judge(newX,newY)) {
			
			DFS(newX,newY);
		}
		//inq[newX][newY]=true;
	}
	return; 
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			scanf("%d",&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++;
				DFS(i,j);
				
			}
		}
	}
	printf("%d",ans);
}

/*
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
*/

再用BFS的非递归算法实现(借助队列)

//BFS用了队列的思想 

#include<cstdio>
#include<queue>
using namespace std;
struct node{
	int x,y;
}Node;
const int maxn = 100;
int n,m,matrix[maxn][maxn];//大小为n*m矩阵 
bool inq[maxn][maxn];
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
//判断是否需要访问,矩阵下标从0开始 
bool judge(int x,int y){
	if(x>=n||x<0||y>=m||y<0)return false;
	if(inq[x][y]==true||matrix[x][y]==0)return false;
	return true;
}
//进行广度优先搜索,即只考虑搜索这一层面 
void BFS(int x,int y){//从(x,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 i=0;i<n;i++){
		for(int j=0;j<m;j++){
			scanf("%d",&matrix[i][j]);
		}
	}
	int ans=0; 
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			if(judge(i,j)){
			//if(matrix[i][j]==1&&inq[i][j]==false){
				ans++;
				BFS(i,j);
				
			}
		}
	}
	printf("%d",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值