There is a directed graph of n nodes, labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph, where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if it has no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Nodes that lie on a cycle, or that can reach a cycle, are not safe. The graph may be disconnected, may contain self-loops, and some nodes may have an empty adjacency list.
Return an array containing all the safe nodes of the graph, sorted in ascending order.
Function Signature
def eventual_safe_nodes(graph: list[list[int]]) -> list[int]:
Rules
-
graph[i]
is the adjacency list of node
i
. An empty list means node
i
is a terminal node.
-
A self-loop (node
i
appearing in
graph[i]
) is a cycle of length one, so that node is not safe.
-
A node is safe only when every path from it ends at a terminal node. Having one path that reaches a terminal node is not enough.
-
Return the safe node labels in ascending order. Return an empty list when no node is safe.
Constraints
-
n == len(graph)
-
1 <= n <= 10^4
-
0 <= len(graph[i]) <= n
-
0 <= graph[i][j] <= n - 1
-
graph[i]
is sorted in strictly increasing order.
-
The graph may contain self-loops.
-
The number of edges in the graph is between 0 and
4 * 10^4
.
Examples
Input: graph = [[1, 2], [2, 3], [5], [0], [5], [], []]
Output: [2, 4, 5, 6]
The edges are 0 -> 1, 0 -> 2, 1 -> 2, 1 -> 3, 2 -> 5, 3 -> 0 and 4 -> 5. Nodes 5 and 6 are terminal nodes, and every path from nodes 2 and 4 ends at node 5. Nodes 0, 1 and 3 lie on the cycle 0 -> 1 -> 3 -> 0.
Input: graph = [[1, 2, 3, 4], [1, 2], [3, 4], [0, 4], []]
Output: [4]
Only node 4 is a terminal node. Node 1 has a self-loop, and nodes 0, 2 and 3 can reach the cycle 0 -> 3 -> 0, so only node 4 is safe.
Input: graph = [[], [0, 2], [2]]
Output: [0]
Node 0 is terminal. Node 2 has a self-loop. Node 1 has a path to node 0, but its other edge leads to node 2 and its self-loop, so node 1 is not safe.