【发布时间】:2021-05-21 16:48:14
【问题描述】:
我正在尝试使用 IDA* 算法和曼哈顿启发式算法来解决 15-Puzzle 问题。 我已经从这个 Wikipedia 页面 (link) 的伪代码中实现了算法。
到目前为止,这是我的代码:
def IDA(initial_state, goal_state):
initial_node = Node(initial_state)
goal_node = Node(goal_state)
threshold = manhattan_heuristic(initial_state, goal_state)
path = [initial_node]
while 1:
tmp = search(path, goal_state, 0, threshold)
if tmp == True:
return path, threshold
elif tmp == float('inf'):
return False
else:
threshold = tmp
def search(path, goal_state, g, threshold):
node = path[-1]
f = g + manhattan_heuristic(node.state, goal_state)
if f > threshold:
return f
if np.array_equal(node.state, goal_state):
return True
minimum = float('inf')
for n in node.nextnodes():
if n not in path:
path.append(n)
tmp = search(path, goal_state, g + 1, threshold)
if tmp == True:
return True
if tmp < minimum:
minimum = tmp
path.pop()
return minimum
def manhattan_heuristic(state1, state2):
size = range(1, len(state1) ** 2)
distances = [count_distance(num, state1, state2) for num in size]
return sum(distances)
def count_distance(number, state1, state2):
position1 = np.where(state1 == number)
position2 = np.where(state2 == number)
return manhattan_distance(position1, position2)
def manhattan_distance(a, b):
return abs(b[0] - a[0]) + abs(b[1] - a[1])
class Node():
def __init__(self, state):
self.state = state
def nextnodes(self):
zero = np.where(self.state == 0)
y,x = zero
y = int(y)
x = int(x)
up = (y - 1, x)
down = (y + 1, x)
right = (y, x + 1)
left = (y, x - 1)
arr = []
for direction in (up, down, right, left):
if len(self.state) - 1 >= direction[0] >= 0 and len(self.state) - 1 >= direction[1] >= 0:
tmp = np.copy(self.state)
tmp[direction[0], direction[1]], tmp[zero] = tmp[zero], tmp[direction[0], direction[1]]
arr.append(Node(tmp))
return arr
我正在使用 3x3 拼图测试此代码,这是无限循环!由于递归,我在测试我的代码时遇到了一些麻烦......
我认为错误可能在这里:tmp = search(path, goal_state, g + 1, threshold)(在search 函数中)。我只在 g 成本值上加了一个。但这应该是正确的,因为我只能将瓷砖移到 1 个位置。
下面是调用IDA()函数的方法:
initial_state = np.array([8 7 3],[4 1 2],[0 5 6])
goal_state = np.array([1 2 3],[8 0 4],[7 6 5])
IDA(initial_state, goal_state)
有人可以帮我解决这个问题吗?
【问题讨论】:
-
您的示例输入是针对
8-puzzle问题的,对吧? -
我得到阈值
24的结果。它没有进入任何无限循环,只是需要时间来收敛!您可以从here 中查看不同算法在求解8-puzzle时的性能。
标签: python graph-algorithm path-finding heuristics sliding-tile-puzzle