【图论】求连通分量

这篇博客介绍了如何求解图的连通分量,提供了包括DFS和BFS在内的五种方法,分别结合邻接表、邻接矩阵以及STL队列进行实现。内容涵盖算法思路、输入输出格式以及样例展示。

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

Description

求一个图的连通分量

无向图

Input

nnn 顶点数(nnn<=100100100)

Output

连通分量

Sample Input
8
6 3
1 2
2 5
5 4
4 1
8 7
0 0
Sample Output
4

思路

这里有五种方法,分别是dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。dfs+bfs+,dfs+,bfs+,bfs++STL
首先是两种读入:

邻接表

 struct whw
{
   
   
	int x,y;
}a[10001];
/*---------------------------------------------------------*/
	scanf("%d%d",&x,&y);
	while (x && y)
	{
   
   
	    a[++m]=(whw){
   
   y,h[x]};h[x]=m;
	    a[++m]=(whw){
   
   x,h[y]};h[y]=m;//因为是无向图,所以x到y和y到x都要赋值
		scanf("%d%d",&x,&y);
	}

邻接矩阵

int h[1005][1005];
/*---------------------------------------------------------*/
	scanf("%d%d",&x,&y); 
	while (x && y)
	{
   
   
	    h[x][y]=h[y][x]=1;//上面
		scanf("%d%d",&x,&y);
	}

还有用STLSTLSTL时要注意:
库:&lt;queue&gt;&lt;queue&gt;<queue>
定义int类型的队列(wh):queue&lt;int&gt;wh;queue&lt;int&gt;wh;queue<int>wh;

还有用法:
(常见的)

用法 作用
### 图论连通分量的概念 在图论领域,连通分量是指在一个无向图中无法再扩展的最大子集,在该子集中任意两点间都至少存在一条路径[^2]。对于有向图,则更关注于强连通分量,即一组顶点集合内部两两可达的情况。 ### Tarjan算法简介 针对有向图中的强连通分量识别问题,Tarjan算法提供了一种高效的解决方案。此算法通过一次深度优先遍历即可完成对整个图结构的扫描,并在此过程中发现所有的强连通分支[^4]。 ### Python实现示例 下面给出一段Python代码片段展示如何使用Tarjan算法查找给定有向图内的所有强连通分量: ```python def tarjan_scc(graph): index_counter = [0] stack = [] lowlink = {} index = {} result = [] def strongconnect(node): # Set the depth index for this node to be the next available index index[node] = index_counter[0] lowlink[node] = index_counter[0] index_counter[0] += 1 stack.append(node) # Consider successors of `node` try: for successor in graph[node]: if successor not in lowlink: # Successor has not yet been visited; recurse on it strongconnect(successor) lowlink[node] = min(lowlink[node], lowlink[successor]) elif successor in stack: # the successor is in the stack and hence in the current SCC lowlink[node] = min(lowlink[node], index[successor]) # If `node` is a root node, pop the stack and generate an SCC if lowlink[node] == index[node]: connected_component = [] while True: successor = stack.pop() connected_component.append(successor) if successor == node: break component = tuple(connected_component) # storing the result result.append(component) except KeyError as e: pass # Node without outgoing edges does not affect SCCs for node in graph.keys(): if node not in lowlink: strongconnect(node) return result ``` 上述函数接受一个邻接表形式表示的有向图为输入参数,并返回由多个元组组成的列表作为输出结果,每个元组代表了一个独立的强连通分量[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值