技术文摘
用 20 行代码借助 Tarjan 算法求解强连通分量
2024-12-31 08:38:15 小编
用 20 行代码借助 Tarjan 算法求解强连通分量
在图论中,强连通分量是一个非常重要的概念。强连通分量是指在有向图中,一个最大的子图,其中任意两个顶点之间都存在路径。求解强连通分量在很多领域都有广泛的应用,比如网络分析、程序优化等。
Tarjan 算法是一种高效的求解强连通分量的算法。下面我们将展示如何用 20 行代码来实现 Tarjan 算法求解强连通分量。
我们需要定义一些数据结构来存储图的信息。我们可以使用邻接表来表示图。
class Graph:
def __init__(self, vertices):
self.V = vertices
self.adj = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.adj[u].append(v)
接下来,我们实现 Tarjan 算法的核心部分。
index = 0
low = [0] * num_vertices
on_stack = [False] * num_vertices
stack = []
scc_count = 0
scc_ids = [0] * num_vertices
def tarjan_scc(graph, vertex):
global index, scc_count
index += 1
low[vertex] = index
stack.append(vertex)
on_stack[vertex] = True
for neighbor in graph.adj[vertex]:
if low[neighbor] == 0:
tarjan_scc(graph, neighbor)
low[vertex] = min(low[vertex], low[neighbor])
elif on_stack[neighbor]:
low[vertex] = min(low[vertex], low[neighbor])
if low[vertex] == index:
scc_count += 1
while stack[-1]!= vertex:
node = stack.pop()
on_stack[node] = False
scc_ids[node] = scc_count
stack.pop()
on_stack[vertex] = False
scc_ids[vertex] = scc_count
最后,我们可以使用以下代码来调用 Tarjan 算法并输出强连通分量的结果。
graph = Graph(5)
graph.add_edge(0, 1)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(1, 3)
graph.add_edge(3, 4)
for vertex in range(graph.V):
if low[vertex] == 0:
tarjan_scc(graph, vertex)
print("强连通分量个数:", scc_count)
for vertex in range(graph.V):
print("顶点", vertex, "属于强连通分量", scc_ids[vertex])
通过这 20 行左右的代码,我们成功地利用 Tarjan 算法求解了强连通分量。希望这个简单的示例能够帮助您理解和应用 Tarjan 算法来解决相关问题。
- Win11 自带截图无法使用的修复方法
- 深入剖析 RedHat 系 Linux 系统中 rpm 与 yum 命令的运用
- CentOS 在虚拟机中添加网卡无法识别的解决办法
- Centos7 取消锁屏的方法及 Centos 系统取消自动锁屏教程
- VMware 虚拟机中 CentOS 分区扩容操作笔记
- CentOS 系统服务器设置 SSH 免密码登录教程
- CentOS 系统中 iSCSI 客户端的安装部署教程
- CentOS 系统中利用 xtables-addons 拒绝 IP 访问的配置方法
- 在硬件不支持的 PC 上安装 Windows11 的方法
- 在 CentOS 中利用 Squid 与 Stunnel 构建代理服务器指南
- Win11 无法识别 Xbox 控制器的修复方法
- VM 虚拟机安装 Win11 系统的详细图文教程
- CentOS 中 tmux 窗口管理程序的安装与使用方法
- Win11 四分窗口的方法:Windows11 窗口四分屏技巧
- CentOS 系统中 Telent 服务的安装与配置基础办法