Created
November 23, 2020 13:13
-
-
Save Alfex4936/d3825d4f38f5f9a9e0450f1da8a3a584 to your computer and use it in GitHub Desktop.
Tarjan's Algorithm to find strongly connected componenets in directed graph in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
UNVISITED = -1 | |
class Graph: | |
global UNVISITED | |
def __init__(self, vertices): | |
self.v = vertices | |
self.g = defaultdict(list) | |
self.id = 0 | |
def addEdge(self, u, v): | |
self.g[u].append(v) | |
def findSCCs(self): | |
ids = [UNVISITED] * self.v | |
low = [UNVISITED] * self.v | |
onStack = [False] * self.v | |
stack = [] | |
for i in range(self.v): | |
if ids[i] == UNVISITED: | |
self.dfs(i, low, ids, onStack, stack) | |
return low | |
def dfs(self, at, low, ids, onStack, stack): | |
ids[at] = self.id | |
low[at] = self.id | |
self.id += 1 | |
onStack[at] = True | |
stack.append(at) | |
for to in self.g[at]: | |
if ids[to] == UNVISITED: | |
self.dfs(to, low, ids, onStack, stack) | |
low[at] = min(low[at], low[to]) | |
elif onStack[to] == True: | |
low[at] = min(low[at], ids[to]) | |
w = UNVISITED | |
if low[at] == ids[at]: | |
print("Strongly Connected Components: ", end="") | |
while w != at: | |
w = stack.pop() | |
print(f"Node {w}", end=" ") | |
onStack[w] = False | |
print() | |
def __str__(self): | |
return self.print() | |
def print(self): | |
for vertice, edge in self.g.items(): | |
print(f"{vertice} ->", *edge) | |
if __name__ == "__main__": | |
g = Graph(8) # 8 vertices | |
g.addEdge(0, 1) | |
g.addEdge(1, 2) | |
g.addEdge(2, 0) | |
g.addEdge(3, 4) | |
g.addEdge(3, 7) | |
g.addEdge(4, 5) | |
g.addEdge(5, 0) | |
g.addEdge(5, 6) | |
g.addEdge(6, 0) | |
g.addEdge(6, 2) | |
g.addEdge(6, 4) | |
g.addEdge(7, 3) | |
g.addEdge(7, 5) | |
# g.print() | |
print(g.findSCCs()) | |
""" Result | |
Strongly Connected Components: Node 2 Node 1 Node 0 | |
Strongly Connected Components: Node 6 Node 5 Node 4 | |
Strongly Connected Components: Node 7 Node 3 | |
low-link = [0, 0, 0, 3, 4, 4, 4, 3] | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment