-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_exists.py
71 lines (53 loc) · 1.69 KB
/
path_exists.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def dfs_path_exists(self, start, end, visited=None):
if visited is None:
visited = set()
visited.add(start)
if start == end:
return True
for neighbor in self.graph[start]:
if neighbor not in visited:
if self.dfs_path_exists(neighbor, end, visited):
return True
return False
def bfs_path_exists(self, start, end):
visited = set()
queue = deque([start])
while queue:
current = queue.popleft()
if current == end:
return True
visited.add(current)
for neighbor in self.graph[current]:
if neighbor not in visited:
queue.append(neighbor)
return False
# Example usage:
# Construct a graph
# 1 -- 2 -- 4
# | |
# v v
# 3 -- 5
graph = Graph()
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 4)
graph.add_edge(2, 5)
graph.add_edge(3, 5)
start_vertex = 1
end_vertex = 4
# Check if a path exists using DFS
if graph.dfs_path_exists(start_vertex, end_vertex):
print(f"Path exists between {start_vertex} and {end_vertex} using DFS.")
else:
print(f"No path exists between {start_vertex} and {end_vertex} using DFS.")
# Check if a path exists using BFS
if graph.bfs_path_exists(start_vertex, end_vertex):
print(f"Path exists between {start_vertex} and {end_vertex} using BFS.")
else:
print(f"No path exists between {start_vertex} and {end_vertex} using BFS.")