A directed graph of n nodes (0 to n - 1) is given as an adjacency list graph, where graph[i] lists the nodes that node i has edges to. A terminal node has no outgoing edges. A node is safe if every path that starts at it ends at a terminal node (or at another safe node). Return all safe nodes in ascending order.
A directed graph of n nodes (0 to n - 1) is given as an adjacency list graph, where graph[i] lists the nodes that node i has edges to. A terminal node has no outgoing edges. A node is safe if every path that starts at it ends at a terminal node (or at another safe node). Return all safe nodes in ascending order.
Example 1:
Input: {"graph":[[1,2],[2,3],[5],[0],[5],[],[]]}
Output: [2,4,5,6]
Constraints:
n==graph.length
1≤n≤104
0≤graph[i].length≤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 is in the range [1,4×104].
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"graph":[[1,2],[2,3],[5],[0],[5],[],[]]}
Each of the 7 nodes must be judged: a node is safe only if no path from it can loop forever.