【问题标题】:Calculate Manhattan distance for n_puzzle problem?计算 n_puzzle 问题的曼哈顿距离?
【发布时间】:2021-11-17 10:30:50
【问题描述】:

我正在尝试计算 n_puzzle 问题中的每个图块,其中图块放错了位置,找到到达正确位置所需的移动次数。

例如3x3 网格,如果图块 1 位于左上角 (0,0),它应该在右下角 (2,2),则需要 4 步才能到达目标。

我以[0, 0, [0, 1, 2], [3, 4, 5], [6, 7, 8]] 的形式保存拼图,其中前两个值表示空白图块零的坐标。到目前为止,我所拥有的是一种计算有多少瓷砖错位的方法:

def GetDist(self):
    if self.value == self.goal:
        return 0
    dist = 0
    for a, b in zip(self.value[2], self.goal[2]):
        for g, t in zip(a, b):
            if g != t:
                dist += 1
    return dist

任何建议将不胜感激!

【问题讨论】:

    标签: python artificial-intelligence manhattan


    【解决方案1】:

    假设错位的瓷砖在位置 (x, y),而正确的位置应该是 (w, z)。将图块移动到正确位置所需的移动次数为:

    n_moves = abs(x - w) + abs(y - z)
    

    【讨论】:

    • 有没有办法有效地找到坐标?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多