All Ancestors of a Node in a Directed Acyclic Graph

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).

You are also given a 2D integer array edges, where edges[i] = [from_i, to_i] denotes a unidirectional edge from node from_i to node to_i.

Return a list answer, where answer[i] is the list of ancestors of the i-th node, sorted in ascending order.

A node u is an ancestor of another node v if u can reach v via a set of edges.

Examples

Example 1

Input: n = 8, edges = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]

Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]

Explanation: Node 0 has no ancestors. Node 3 has ancestors 0 and 1. Node 5 has ancestors 0, 1, and 3 (since 0->3->5 and 1->3->5). Node 7 has ancestors 0, 1, 2, and 3.

Example 2

Input: n = 5, edges = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]]

Explanation: This is a fully connected DAG. Each node i has all nodes 0 through i-1 as ancestors.

Constraints

  • 1 <= n <= 1000
  • 0 <= edges.length <= min(2000, n * (n - 1) / 2)
  • edges[i].length == 2
  • 0 <= from_i, to_i <= n - 1
  • from_i != to_i
  • There are no duplicate edges.
  • The graph is a DAG (directed and acyclic).
Source: Topological Sort pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle