There is a directed graph of n nodes with each node 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 there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or is a terminal node itself).
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: Nodes 5 and 6 are terminal nodes (no outgoing edges). Node 2 leads to node 5 (safe). Node 4 leads to node 5 (safe). Nodes 0, 1, and 3 are part of a cycle 0 -> 1 -> 3 -> 0, so they are not safe.
Example 2:
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation: Only node 4 is a terminal node. Nodes 0, 1, 2, and 3 are all part of cycles or lead to cycles, so the only safe node is node 4.
Example 3:
Input: graph = [[],[0,2,3,4],[3],[4],[]]
Output: [0,1,2,3,4]
Explanation: Node 0 and node 4 are terminal nodes. All other nodes eventually lead to terminal nodes only, so every node is safe.
n == graph.length1 <= n <= 100000 <= graph[i].length <= n0 <= graph[i][j] <= n - 1graph[i] is sorted in strictly increasing order[1, 4 * 10000]