-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathall-paths-from-source-lead-to-destination.py
More file actions
47 lines (31 loc) · 1.06 KB
/
all-paths-from-source-lead-to-destination.py
File metadata and controls
47 lines (31 loc) · 1.06 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
41
42
43
44
45
46
47
from enum import Enum
from typing import List
class Color(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
class Solution:
def build_adj_list(self, n: int, edges: List[List[int]]) -> List[List[int]]:
adj_list: List[List[int]] = [[] for _ in range(n)]
for src, dst in edges:
adj_list[src].append(dst)
return adj_list
def leadsToDestination(
self, n: int, edges: List[List[int]], source: int, destination: int
) -> bool:
adj_list = self.build_adj_list(n, edges)
colors = [Color.WHITE] * n
def dfs(node: int) -> bool:
if colors[node] == Color.GRAY:
return False
if colors[node] == Color.BLACK:
return True
colors[node] = Color.GRAY
result = True
if not adj_list[node]:
result = node == destination
for next_node in adj_list[node]:
result = result and dfs(next_node)
colors[node] = Color.BLACK
return result
return dfs(source)