Python实现强连通分量算法——Tarjan算法

Python实现强连通分量算法——Tarjan算法

Tarjan算法是一种基于深度优先搜索(DFS)的强连通分量(SCC)查找算法,由Robert Tarjan在1972年提出。它采用了栈(Stack)数据结构来记录已发现但未处理完的节点,并通过对每个节点进行DFS遍历来寻找强连通分量。

以下是Python实现的Tarjan算法的完整源码:

# -*- coding: utf-8 -*-

def tarjan(graph):
    index_counter = [0]
    stack = []
    lowlink = {}
    index = {}
    result = []

    def strongconnect(node):
        # set the depth index for this node to the smallest unused index
        index[node] = index_counter[0]
        lowlink[node] = index_counter[0]
        index_counter[0] += 1
        stack.append(node)

        # Consider successors of `node`
        try:
            successors = graph[node]
        except:
    

你可能感兴趣的:(算法,深度优先,python)