-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.py
More file actions
40 lines (30 loc) · 1.16 KB
/
2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.py
File metadata and controls
40 lines (30 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# time complexity: O(n^2 + n*m)
# space complexity: O(n+m)
from typing import List
class Solution:
def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
adjacencyList = [[] for _ in range(n)]
for edge in edges:
fromNode, toNode = edge
adjacencyList[toNode].append(fromNode)
ancestorsList = []
for i in range(n):
ancestors = []
visited = set()
self.findChildren(i, adjacencyList, visited)
for node in range(n):
if node == i:
continue
if node in visited:
ancestors.append(node)
ancestorsList.append(ancestors)
return ancestorsList
def findChildren(self, currentNode, adjacencyList, visitedNodes):
visitedNodes.add(currentNode)
for neighbour in adjacencyList[currentNode]:
if neighbour not in visitedNodes:
self.findChildren(neighbour, adjacencyList, visitedNodes)
n = 8
edgeList = [[0, 3], [0, 4], [1, 3], [2, 4],
[2, 7], [3, 5], [3, 6], [3, 7], [4, 6]]
print(Solution().getAncestors(n, edgeList))