Skip to content

Commit 8243f26

Browse files
authored
Update all-ancestors-of-a-node-in-a-directed-acyclic-graph.py
1 parent b290a73 commit 8243f26

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

Python/all-ancestors-of-a-node-in-a-directed-acyclic-graph.py

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,43 @@ def iter_dfs(adj, i, result):
3232

3333
# Time: O(|V| * |E| * log(|V| * |E|))
3434
# Space: O(|V| * |E|)
35-
# topological sort
35+
# bfs
3636
class Solution2(object):
37+
def getAncestors(self, n, edges):
38+
"""
39+
:type n: int
40+
:type edges: List[List[int]]
41+
:rtype: List[List[int]]
42+
"""
43+
def bfs(adj, i, result):
44+
lookup = [False]*len(adj)
45+
q = [i]
46+
lookup[i] = True
47+
while q:
48+
new_q = []
49+
for u in q:
50+
for v in adj[u]:
51+
if lookup[v]:
52+
continue
53+
lookup[v] = True
54+
new_q.append(v)
55+
result[i].append(v)
56+
q = new_q
57+
result[i].sort()
58+
59+
adj = [[] for _ in xrange(n)]
60+
for u, v in edges:
61+
adj[v].append(u)
62+
result = [[] for _ in xrange(n)]
63+
for u in xrange(n):
64+
bfs(adj, u, result)
65+
return result
66+
67+
68+
# Time: O(|V| * |E| * log(|V| * |E|))
69+
# Space: O(|V| * |E|)
70+
# topological sort
71+
class Solution3(object):
3772
def getAncestors(self, n, edges):
3873
"""
3974
:type n: int

0 commit comments

Comments
 (0)