Skip to content

Commit 228058d

Browse files
authored
Create all-paths-from-source-lead-to-destination.py
1 parent 5bd9fe2 commit 228058d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Time: O(n + e)
2+
# Space: O(n + e)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def leadsToDestination(self, n, edges, source, destination):
9+
"""
10+
:type n: int
11+
:type edges: List[List[int]]
12+
:type source: int
13+
:type destination: int
14+
:rtype: bool
15+
"""
16+
UNVISITED, VISITING, DONE = range(3)
17+
def dfs(children, node, destination, status):
18+
if status[node] == DONE:
19+
return True
20+
if status[node] == VISITING:
21+
return False
22+
status[node] = VISITING
23+
if node not in children and node != destination:
24+
return False
25+
if node in children:
26+
for child in children[node]:
27+
if not dfs(children, child, destination, status):
28+
return False
29+
status[node] = DONE
30+
return True
31+
32+
children = collections.defaultdict(list)
33+
for parent, child in edges:
34+
children[parent].append(child)
35+
return dfs(children, source, destination, [0]*n)

0 commit comments

Comments
 (0)