-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1971.py
30 lines (26 loc) · 891 Bytes
/
Solution1971.py
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
class Solution(object):
def validPath(self, n, edges, source, destination):
"""
:type n: int
:type edges: List[List[int]]
:type source: int
:type destination: int
:rtype: bool
"""
# Build adjacency list representation of the graph
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
# Perform DFS
visited = set()
return self.dfs(source, destination, graph, visited)
def dfs(self, current, destination, graph, visited):
if current == destination:
return True
visited.add(current)
for neighbor in graph[current]:
if neighbor not in visited:
if self.dfs(neighbor, destination, graph, visited):
return True
return False