Practice/Amazon/Leetcode 2192. All Ancestors of a Node in a Directed Acyclic Graph
CodingOptional
You are given a directed acyclic graph (DAG) with n nodes labeled from 0 to n - 1, and an array of edges where each edges[i] = [from, to] represents a directed edge from node from to node to.
Your task is to determine, for each node in the graph, which nodes can reach it by following directed edges. In other words, find all ancestors of each node. An ancestor of node x is any node y such that there exists a directed path from y to x.
Return a list where the element at index i contains a sorted list of all ancestors of node i.
1 <= n <= 10000 <= edges.length <= min(2000, n * (n - 1) / 2)edges[i].length == 20 <= from, to < nfrom != toExample 1:
` Input: n = 5, edges = [[0,1],[0,2],[1,3],[2,3],[2,4]] Output: [[],[0],[0],[0,1,2],[0,2]]
Explanation:
Example 2:
` Input: n = 4, edges = [[0,1],[1,2],[2,3]] Output: [[],[0],[0,1],[0,1,2]]
Explanation: This is a simple chain where each node inherits all ancestors from its predecessor. `
Example 3:
` Input: n = 3, edges = [[0,2],[1,2]] Output: [[],[],[0,1]]
Explanation: Node 2 has two direct parents (0 and 1), and they become its ancestors. `