The directed graph has nodes numbered from 0 through n-1. Each list graph[i] contains the destinations of outgoing edges from node i. A terminal node has no outgoing edges. A node is safe if every possible sequence of outgoing moves from it eventually ends at a terminal node. Thus a node is unsafe if it can reach a directed cycle, including a self-loop. Return all safe node numbers in increasing order. Terminal nodes themselves are safe.
Example 1:
Input: graph = [[1],[2],[]]
Output: [0,1,2]Explanation: Node 2 is terminal. Node 1 can only move to 2, and node 0 can only move through 1 to 2. All three nodes are safe.
Example 2:
Input: graph = [[1],[0],[]]
Output: [2]Explanation: Nodes 0 and 1 form a directed cycle, so neither is safe. Node 2 has no outgoing edges and is safe, giving [2].
Example 3:
Input: graph = [[0,1],[]]
Output: [1]Explanation: Node 0 can move to terminal node 1, but it can also follow its self-loop forever. Because every possible path must end, node 0 is unsafe. Only node 1 is safe.
Constraints:
1 <= n <= 10000- Each adjacency list contains between
0andnnode numbers, sorted in strictly increasing order. - Each node number is between
0andn-1. - The total number of directed edges is between
1and40000. - Self-loops are allowed.