-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdls.py
More file actions
40 lines (31 loc) · 981 Bytes
/
dls.py
File metadata and controls
40 lines (31 loc) · 981 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
#Iterative Depth-Limited Search (DLS)
def depth_limited_search_iterative(graph, start, goal, depth_limit):
stack = [(start, 0)] # Stack contains tuples of (node, current_depth)
while stack:
node, depth = stack.pop()
# Print visited node
print(node, end=" ")
# Goal check
if node == goal:
print("\nGoal found!")
return True
# Expand node only if depth limit is not reached
if depth < depth_limit:
for neighbor in reversed(graph.get(node, [])): # Reverse to maintain correct order
stack.append((neighbor, depth + 1))
print("\nGoal not found within depth limit.")
return False
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': ['H'],
'F': [],
'G': [],
'H': []
}
depth_limit = 3
goal_node = 'H'
print("Iterative DLS Search:")
depth_limited_search_iterative(graph, 'A', goal_node, depth_limit)