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%)
2
class Solution:
3
def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
4
graph = {}
5
for a, b in edges:
6
graph[b] = graph.get(b, []) + [a]
7
op = [[] for i in range(n)]
8
for a in graph:
9
visited = set()
10
paths = [a]
11
while len(paths) > 0:
12
curr = paths.pop()
13
for b in graph.get(curr, []):
14
if b not in visited:
15
visited.add(b)
16
paths.append(b)
17
op[a] = sorted(visited)
18
return op

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0