写了一个A *实现来解决8-puzzle游戏。由于某种原因,该算法适用于不太复杂的谜题。我尝试了最糟糕的案例拼图,它返回了非最佳结果。是我的启发式错误还是我的堆弹出错误的值,可能是错的?
最坏情况:
shell.sh
这是我的代码
[[8,6,7],[2,5,4],[3,0,1]]
节点类
def ast(board, isDraw):
""" Computes the steps to solve the puzzle using A*
RETURNS: Path, Depth of Node, Max Depth of graph, Number of Expanded nodes, time algorithm finished"""
solvedBoard = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] # SolvedBoard
maxDepth = 0
nodesExpanded = 0
open = list()
opend = dict()
closed = list()
closedd = dict()
# Find where 0 is on board
for row in range(3):
for column in range(3):
if 0 == board[row][column]:
posn = [row, column]
root = Node(list(), board, posn, 0, f=0)
heapq.heappush(open, root)
opend[hash(root)] = root
while len(open) > 0:
node = heapq.heappop(open)
del(opend[hash(node)])
nodesExpanded += 1
for child in node.getChildren():
maxDepth = max(child.depth, maxDepth)
if child.board == solvedBoard:
finishedTime = time.clock()
return (child.path, child.depth, maxDepth, nodesExpanded, finishedTime)
else:
if hash(child) in opend.keys() and opend[hash(child)] < child.f:
continue
if hash(child) in closedd.keys() and closedd[hash(child)] < child.f:
continue
heapq.heappush(open,child)
opend[hash(child)] = child
heapq.heappush(closed, node)
closedd[hash(node)] = node
finishedTime = time.clock()
return ("There is no solution for this configuration of the board","?",maxDepth,nodesExpanded,finishedTime)