-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathall-paths-from-source-lead-to-destination.py
More file actions
35 lines (31 loc) · 1.08 KB
/
all-paths-from-source-lead-to-destination.py
File metadata and controls
35 lines (31 loc) · 1.08 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
# Time: O(n + e)
# Space: O(n + e)
import collections
class Solution(object):
def leadsToDestination(self, n, edges, source, destination):
"""
:type n: int
:type edges: List[List[int]]
:type source: int
:type destination: int
:rtype: bool
"""
UNVISITED, VISITING, DONE = range(3)
def dfs(children, node, destination, status):
if status[node] == DONE:
return True
if status[node] == VISITING:
return False
status[node] = VISITING
if node not in children and node != destination:
return False
if node in children:
for child in children[node]:
if not dfs(children, child, destination, status):
return False
status[node] = DONE
return True
children = collections.defaultdict(list)
for parent, child in edges:
children[parent].append(child)
return dfs(children, source, destination, [0]*n)