-2
假設代碼puzzle.extensions(self)
已被定義,它將返回一個列表,該拼圖的可用解決方案,但沒有確定是否解決。另外puzzle.is_solved(self)
已被定義,它將確定此解決方案是否已解決。這是我需要寫的代碼,我也做了一些不正確的作品。深度第一次搜索解決拼圖
def depth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child containing an extension of the puzzle
in its parent. Return None if this is not possible.
@type puzzle: Puzzle
@rtype: PuzzleNode
"""
stack = [puzzle]
while stack:
k = stack.pop()
for puzzle1 in puzzle.extensions():
if not puzzle1.is_solved():
stack+=[k,puzzle1]
if puzzle1.is_solved():
p = stack.pop()
end_node = PuzzleNode(k,None, p)
k = stack.pop()
last_node = PuzzleNode(p,end_node,k)
while stack:
k = p
p = stack.pop()
cur_node = PuzzleNode(k, last_node, p)
last_node = cur_node
return cur_node
def __init__(self, puzzle=None, children=None, parent=None):
"""
Create a new puzzle node self with configuration puzzle.
@type self: PuzzleNode
@type puzzle: Puzzle | None
@type children: list[PuzzleNode]
@type parent: PuzzleNode | None
@rtype: None
"""
self.puzzle, self.parent = puzzle, parent
if children is None:
self.children = []
else:
self.children = children[:]
嗯,我在砌運行這些模塊,它總是在等待結果,並沒有任何反應,所以任何人都可以告訴我,我聽錯了?