Leetcode Problem 2192. All Ancestors of a Node in a Directed Acyclic Graph
2192. All Ancestors of a Node in a Directed Acyclic Graph
Leetcode Solutions
DFS-based Ancestor Discovery
Create an adjacency list to represent the graph.
Initialize an empty list for each node to store its ancestors.
For each node, perform a DFS:
a. During the DFS, for each node visited, if it is not the starting node, add the starting node to its ancestors list.
b. Continue the DFS for all unvisited children of the current node.
c. Optionally, use a visited set or check the last ancestor to avoid duplicates.
After completing the DFS for all nodes, return the list of ancestors for each node.