All Ancestors of a Node in a Directed Acyclic Graph LeetCode solution in Python
1# Runtime: 2132 ms (Top 14.62%) | Memory: 30.4 MB (Top 89.89%)2class Solution:3def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:4graph = {}5for a, b in edges:6graph[b] = graph.get(b, []) + [a]7op = [[] for i in range(n)]8for a in graph:9visited = set()10paths = [a]11while len(paths) > 0:12curr = paths.pop()13for b in graph.get(curr, []):14if b not in visited:15visited.add(b)16paths.append(b)17op[a] = sorted(visited)18return op