Skip to content

Commit 4444560

Browse files
authored
Create Find if Path Exists in Graph - Leetcode 1971.py
1 parent 8e89da7 commit 4444560

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# DFS with Recursion
2+
class Solution:
3+
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
4+
if source == destination:
5+
return True
6+
7+
graph = defaultdict(list)
8+
for u, v in edges:
9+
graph[u].append(v)
10+
graph[v].append(u)
11+
12+
seen = set()
13+
seen.add(source)
14+
15+
def dfs(i):
16+
if i == destination:
17+
return True
18+
19+
for nei_node in graph[i]:
20+
if nei_node not in seen:
21+
seen.add(nei_node)
22+
if dfs(nei_node):
23+
return True
24+
25+
return False
26+
27+
return dfs(source) # Time: O(N + E), Space: O(N + E)
28+
29+
# Iterative DFS with Stack
30+
31+
class Solution:
32+
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
33+
if source == destination:
34+
return True
35+
36+
graph = defaultdict(list)
37+
for u, v in edges:
38+
graph[u].append(v)
39+
graph[v].append(u)
40+
41+
seen = set()
42+
seen.add(source)
43+
stack = [source]
44+
45+
while stack:
46+
node = stack.pop()
47+
if node == destination:
48+
return True
49+
for nei_node in graph[node]:
50+
if nei_node not in seen:
51+
seen.add(nei_node)
52+
stack.append(nei_node)
53+
54+
return False # Time: O(N + E), Space: O(N + E)
55+
56+
57+
# BFS with Deque
58+
59+
from collections import deque
60+
class Solution:
61+
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
62+
if source == destination:
63+
return True
64+
65+
graph = defaultdict(list)
66+
for u, v in edges:
67+
graph[u].append(v)
68+
graph[v].append(u)
69+
70+
seen = set()
71+
seen.add(source)
72+
q = deque()
73+
q.append(source)
74+
75+
while q:
76+
node = q.popleft()
77+
if node == destination:
78+
return True
79+
for nei_node in graph[node]:
80+
if nei_node not in seen:
81+
seen.add(nei_node)
82+
q.append(nei_node)
83+
84+
return False # Time: O(N + E), Space: O(N + E)

0 commit comments

Comments
 (0)