cs471/hw1/dfs.py

43 lines
1.2 KiB
Python
Raw Normal View History

2019-01-24 02:51:33 -05:00
#!/usr/bin/env python3
2019-01-24 11:08:22 -05:00
import problem
2019-01-24 02:51:33 -05:00
2019-01-24 15:56:28 -05:00
def depth_limited_search(node, depth):
2019-01-24 02:51:33 -05:00
if depth == 0:
2019-01-24 11:08:22 -05:00
if problem.is_goal(node):
2019-01-24 15:56:28 -05:00
return (node, True)
return (None, True)
2019-01-24 02:51:33 -05:00
elif depth > 0:
2019-01-24 15:56:28 -05:00
print("Depth is now " + str(depth))
if node == problem.start:
print("Initial state")
print(node.to_string())
2019-01-24 02:51:33 -05:00
any_remaining = False
for act in node.actions:
child = act.result_state
2019-01-24 15:56:28 -05:00
print(act.to_string())
print(child.to_string())
found, remaining = depth_limited_search(child, depth - 1)
2019-01-24 02:51:33 -05:00
if found is not None:
2019-01-24 15:56:28 -05:00
print("Goal state found")
return (found, True)
2019-01-24 02:51:33 -05:00
if remaining:
any_remaining = True
2019-01-24 15:56:28 -05:00
return (None, any_remaining)
2019-01-24 02:51:33 -05:00
def iterative_deepening_dfs(root):
2019-01-24 15:56:28 -05:00
for depth in range(1, 999):
print("Examining at maximum depth " + str(depth))
found, remaining = depth_limited_search(root, depth)
2019-01-24 02:51:33 -05:00
if found is not None:
2019-01-24 15:56:28 -05:00
return found
2019-01-24 02:51:33 -05:00
elif not remaining:
2019-01-24 15:56:28 -05:00
return None
2019-01-24 02:51:33 -05:00
print("Overflow in iterative deepening depth-first search")
2019-01-24 11:08:22 -05:00
2019-01-24 15:56:28 -05:00
finish = iterative_deepening_dfs(problem.start)
2019-01-24 11:08:22 -05:00
print(finish.to_string())