Imagine you have a family tree or a company hierarchy represented as a directed graph where edges show direct relationships. Your task is to find all the ancestors (predecessors) for each person or position in the hierarchy.
You are given a positive integer n representing the number of nodes in a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1.
You are also given a 2D integer array edges, where edges[i] = [from_i, to_i] denotes that there is a unidirectional edge from from_i to to_i in the graph.
Goal: 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 (there exists a path from u to v).
Input & Output
Visualization
Time & Space Complexity
We perform DFS from each of the n nodes, each DFS takes O(V + E) time
Space for adjacency list, visited set, and result storage
Constraints
- 1 โค n โค 1000
- 0 โค edges.length โค min(2000, n ร (n - 1) / 2)
- edges[i].length == 2
- 0 โค fromi, toi โค n - 1
- fromi โ toi
- There are no duplicate edges
- The graph is acyclic