📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / ICPC-Referat / Material / tarjans-short.py
132932 viewsLicense: OTHER
def strongly_connected_components(graph):1index_counter = 02stack = []3lowlinks = {}4index = {}5result = []67def strongconnect(node, index_counter):8index[node] = index_counter9lowlinks[node] = index_counter10index_counter += 111stack.append(node)1213try:14successors = graph[node]15except:16successors = []1718# Depth first search19for successor in successors:20# Does the current node point to a node that was already21# visited?22if successor not in lowlinks:23# Successor has not yet been visited; recurse on it24strongconnect(successor, index_counter)25lowlinks[node] = min(lowlinks[node], lowlinks[successor])26elif successor in stack:27# the successor is in the stack and hence in the28# current strongly connected component (SCC)29lowlinks[node] = min(lowlinks[node], index[successor])3031# If `node` is a root node, pop the stack and generate an SCC32if lowlinks[node] == index[node]:33connected_component = []3435while True:36successor = stack.pop()37connected_component.append(successor)38if successor == node:39break4041component = tuple(connected_component)4243# storing the result44result.append(component)4546for node in graph:47if node not in lowlinks:48strongconnect(node, index_counter)4950return result515253