数据结构——广度优先/深度优先遍历

本文介绍了一种使用广度优先搜索(BFS)和深度优先搜索(DFS)算法来查找图中连通分量的方法。通过实例演示了如何在给定节点数和边数的情况下,构建图的关系矩阵,并利用DFS和BFS遍历所有节点,打印出连通分量。此算法适用于计算机科学和数据结构课程的学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstring> 
#include <queue>
using namespace std;
int n,m,v[11],Map[11][11];

//用广度优先和深度优先搜素实现求联通分量
//结点从0开始命名 
//map数组是图的关系矩阵,v数组是是否遍历过 

void DFS(int x)//深度优先:操作当下(打印)->找到下一个 
{
	cout<<' '<<x;
	for(int i=0; i<n; i++)
	{
		if(!v[i]&&Map[x][i]==1)
		{
			v[i]=1;//注意,一定是先标记遍历过,再去递归搜索 
			DFS(i);
		}
	}
}
void BFS(int x)//广度优先搜索:初始化队列后,拿出队头(并打印),把有联系的元素全部入队 
{
	int y;
	queue<int> Q;
	Q.push(x);
	while(!Q.empty())
	{
		y=Q.front();
		cout<<' '<<y;
		Q.pop();
		for(int i=0;i<n;i++)
		{
			if(!v[i]&&Map[y][i]==1)
			{
				v[i]=1;//入队列之前一定要先标记 
				Q.push(i);
			}
		}
	}
}
int main()
{
	int x,y;
	cout<<"Please input two fingures,one represents the count of node,the other present the count of link"<<endl;
	cin>>n>>m;
	memset(Map,0,sizeof(Map));
	memset(v,0,sizeof(v));
	cout<<"Please input corresponding arrays prensents linkage,each array contain two figures,and each fingure must be limited in the first figure you input just now"<<"\n";
	while(m--)
	{
		cin>>x>>y;
		Map[x][y]=Map[y][x]=1;
	}
	cout<<"This is results of DFS:"<<endl;
	for(int i=0;i<n;i++)
	{
		if(v[i]==0)//对每个没有遍历过的结点进行深度优先搜素 
		{
			v[i]=1;
			cout<<"{";
			DFS(i);
			cout<<"}"<<endl;
		}
	}
	memset(v,0,sizeof(v));
	cout<<"This is results of BFS:"<<endl;
	for(int i=0; i<n; i++)
	{
		if(v[i]==0)
		{
			v[i]=1;
			cout<<"{";
			BFS(i);
			cout<<"}"<<endl;
		}
	}
	return 0;
}








 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值