Example 1
- Input
- graph = [[1,2],[2,3],[5],[0],[5],[],[]]
- Output
- [2,4,5,6]
Nodes 0, 1 and 3 form a cycle. Nodes 2 and 4 go only to terminal 5, and 6 is terminal. An exit from the cycle to 2 does not make cycle nodes safe.
Return the directed graph nodes from which every possible walk eventually reaches a terminal node. Any node that can reach a directed cycle is unsafe.
The adjacency list graph describes nodes 0 through n - 1: each value in graph[u] is the destination of an edge from u. A terminal node has no outgoing edges. A node is safe if every possible path starting there eventually terminates.
Return all safe nodes in ascending order. Self-loops are allowed. One terminating choice is insufficient: if another choice can enter a cycle, the node is unsafe.
n == graph.length; 1 <= n <= 10^40 <= graph[u].length <= n; destinations are in [0, n - 1].1 <= total number of edges <= 4 * 10^4Nodes 0, 1 and 3 form a cycle. Nodes 2 and 4 go only to terminal 5, and 6 is terminal. An exit from the cycle to 2 does not make cycle nodes safe.
The smallest graph has one self-loop. A walk can stay at 0 forever, so its singleton SCC is cyclic and unsafe.
Node 1 loops to itself. Node 0 can choose terminal 2 but can also choose 1, so unsafety propagates to 0. Only 2 is safe.
A strongly connected component (SCC) groups nodes that can all reach each other. A component with several nodes contains a cycle; a singleton is cyclic only if it has a self-loop. In Example 1, {0,1,3} is cyclic, while 2, 4, 5 and 6 cannot reach it. Tarjan finds these groups in one DFS. Reverse the edges between groups and spread an unsafe mark backward from every cyclic group to all groups that can reach it.
Reveal Tarjan SCC: intuition, complexity, and code
Collapse mutual reachability into components, classify the cyclic ones locally, and propagate their consequences through the acyclic component graph.