我正在尝试使用迭代深化深度优先搜索来创建RushHour拼图解算器。现在,当我执行脚本时,它会生成太多节点并快速占用整个内存(分配速度大约为20MB / s)。我知道我存储板状态的解决方案并不完美但不应该吃太多内存。 (整个项目可以在这里找到 here)
import map from node import Node
def all_moves(node): # returns all valid moves for node
state = node.state
output = []
for i in state.cars:
car_id = i[0]
y = i[1]
x = i[2]
for action in actions:
movement = state.is_movable(action, y, x)
if movement[1] != 0:
movement.append(car_id)
movement.append(action)
output.append(movement)
return output
def generate_all_child(node): # creates every new state based on list of valid moves and makes it a child
for move in all_moves(node):
action = move[-1]
car = move[0]
car_id = move[-2]
for step in range(1, move[1]+1):
child_state = node.state.action(car_id, car, action, step)
child_node = Node(child_state, node)
node.add_child(child_node)
def dls(node, node_depth):
if node_depth >= 0:
generate_all_child(node)
if node.state.is_solved():
return node
for child in node.children:
dls(child, node_depth-1)
stack = [] actions = ["left", "right", "up", "down"]
mapa = map.Map() mapa.load("krizovatka.csv") mapa.display_matrix() mapa.load_cars() root = Node(mapa, None) stack.append(root)
depth = 5 for i in range(1, depth+1):
print(i)
final = dls(root, i)
print(len(root.children))
答案 0 :(得分:0)
问题是is_solved()(map.py)中的错误。即使最终状态发生,它也返回0,所以它永远不会停止搜索。现在它有效,虽然速度很慢,但这是一个不同的问题。