-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathfind.py
29 lines (24 loc) · 842 Bytes
/
find.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
29
from collections import deque, defaultdict
from typing import List
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
if source == destination:
return True
# Build the graph
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
# BFS to check path
visited = set()
queue = deque([source])
while queue:
node = queue.popleft()
if node == destination:
return True
if node not in visited:
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
return False