You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# If `node` is a root node, pop the stack and generate an SCC
43
+
iflowlinks[node] ==indexes[node]:
44
+
connected_component= []
45
+
46
+
whileTrue:
47
+
successor=stack.pop()
48
+
connected_component.append(successor)
49
+
ifsuccessor==node:
50
+
break
51
+
components.append(connected_component)
52
+
53
+
fornodeingraph:
54
+
ifnodenotinindexes:
55
+
strongconnect(node)
56
+
57
+
returncomponents
58
+
59
+
# Accept dynamic input for the graph
60
+
graph=defaultdict(list)
61
+
num_nodes=int(input("Enter the number of nodes: "))
62
+
foriinrange(num_nodes):
63
+
node=int(input(f"Enter the successors of node {i}: "))
64
+
successors=list(map(int, input().split()))
65
+
graph[node] =successors
66
+
67
+
print("Strongly Connected Components:")
68
+
print(tarjan(graph))
69
+
70
+
71
+
72
+
""" Explanation:->
73
+
74
+
1) Tarjan's algorithm performs a DFS on the graph to find strongly connected components.
75
+
76
+
2) It maintains an index (incremented for each visited node), a stack of visited nodes, and a lowlink value for each node (lowest index reachable from that node).
77
+
78
+
3) When visiting a node, if any successor is in the stack, the lowlink is updated to be the minimum of its current value and the successor's index.
79
+
80
+
4) If the lowlink of a node equals its own index, it is a root node and the current stack represents an SCC. This SCC is popped from the stack and added to the final components list.
81
+
82
+
5) After Tarjan's finishes, the components list contains all the SCCs in the graph."""
0 commit comments