Skip to content

Instantly share code, notes, and snippets.

@siddhantmedar
Created July 25, 2022 05:26
Show Gist options
  • Save siddhantmedar/96b0307b8a57423662c506f0bf6a2b9a to your computer and use it in GitHub Desktop.
Save siddhantmedar/96b0307b8a57423662c506f0bf6a2b9a to your computer and use it in GitHub Desktop.
Tarjan's Algorithm for finding SCC in graph
def dfs(graph, node):
global timer
visited.add(node)
timer += 1
disc[node] = low[node] = timer
inStack[node] = True
st.append(node)
for nei in graph[node]:
if nei not in visited:
dfs(graph, nei)
low[node] = min(low[node], low[nei])
elif nei in visited and inStack[nei]:
low[node] = min(low[node], disc[nei])
if disc[node] == low[node]:
tmp = []
while st and st[-1] != node:
itm = st.pop()
tmp.append(itm)
inStack[itm] = False
tmp.append(node)
st.pop()
res.append(tmp)
N = 7
graph = {
1: [2],
2: [3],
3: [4],
4: [2, 5],
5: [6],
6: [7],
7: [6]
}
disc = {}
low = {}
inStack = {}
st = []
visited = set()
timer = 0
res = []
for i in range(1, N + 1):
if i not in visited:
dfs(graph, i)
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment