Graphs Topological sort
459. Find Eventual Safe States
You are given a directed graph with n nodes, numbered from 0 to n - 1. graph[i] lists the nodes that
node i has an edge to. An edge can be followed only in its own direction, from i to a node in graph[i].
A node is terminal if no edge leaves it, so its list is empty. A node is safe if every path that starts at it ends at a terminal node. A path that can go round a cycle keeps going for ever and never ends, so a node where such a path starts is not safe. A terminal node is safe, since every path from it ends at once.
Return all the safe nodes in ascending order.
Example 1
Input: graph = [[1, 4], [2], [3], [], [5], [4], [3]]
[1,2,3,6]Explanation: Node 3 is terminal. Nodes 1, 2 and 6 lead only to node 3, so they are safe. Nodes 4 and 5 point to each other for ever. Node 0 is not safe: one path goes to 1 and ends, but another goes to 4 and never ends.
Example 2
Input: graph = [[0, 1], [2], []]
[1,2]Explanation: Node 0 has an edge to itself, so a path from 0 can stay at 0 for ever. Nodes 1 and 2 lead only to the terminal node 2.
Example 3
Input: graph = [[1], [2], [0], [0]]
[]Explanation: There is no terminal node. Nodes 0, 1 and 2 form a cycle, and node 3 leads into it, so no node is safe.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n == graph.length ≤ 1050 ≤ graph[i][j] < n- The values in each
graph[i]are distinct, in any order.graph[i]may containiitself. - All the lists together hold at most 2 × 105 edges.
Clarifying questions
What you would ask an interviewer before writing any code.