-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_2_dfs.py
More file actions
49 lines (39 loc) · 1006 Bytes
/
Copy path2_2_dfs.py
File metadata and controls
49 lines (39 loc) · 1006 Bytes
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
# -*- coding: utf-8 -*-
"""2.2.DFS.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1Lej7jDexY081i8y3feim7unS5LcVqZcz
"""
def dfs(graph, start, goal, path=None, visited=None):
if path is None:
path = [start]
if visited is None:
visited = set()
visited.add(start)
if start == goal:
return path
for neighbor in graph.get(start, []):
if neighbor not in visited:
new_path = dfs(graph, neighbor, goal, path + [neighbor], visited)
if new_path:
return new_path
return None # If no path is found
# Define the graph
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
# Start and goal nodes
start_node = 'A'
goal_node = 'F'
# Run DFS
result = dfs(graph, start_node, goal_node)
# Print the result
if result:
print("Path found:", " -> ".join(result))
else:
print("No path found.")