-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
37 lines (30 loc) · 833 Bytes
/
dfs.py
File metadata and controls
37 lines (30 loc) · 833 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
#Recursive DFS (AI Style Search)
def dfs_recursive(graph, node, goal, visited=None):
if visited is None:
visited = set()
# Mark the node as visited
visited.add(node)
print(node, end=" ")
# Check if the goal is found
if node == goal:
print("\nGoal found!")
return True
# Explore neighbors
for neighbor in graph[node]:
if neighbor not in visited:
if dfs_recursive(graph, neighbor, goal, visited):
return True # Goal found, stop further exploration
return False # Goal not found in this path
#Example Usage (AI Graph Search Scenario)
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': ['H'],
'F': [],
'G': [],
'H': []
}
print("Recursive DFS:")
dfs_recursive(graph, 'A', 'H')