【问题标题】:Can somebody explain in Manhattan dstance for the 8 puzzle in java for me?有人可以在曼哈顿为我解释 Java 中的 8 谜题吗?
【发布时间】:2013-11-15 05:04:12
【问题描述】:

我正在编写一个 A* 算法,它可以解决 Java 中的 8 个难题,到目前为止,我已经使用不合适的图块数量实现了 DFS、BFS、A*,我只需要使用启发式算法来实现它曼哈顿距离。

您可能知道,曼哈顿距离是每个瓦片相对于其当前位置及其在目标状态中的索引的位移之和。

我在谷歌上搜索并找到了这些关于流程主题的堆栈:

Calculating Manhattan Distance Manhattan distance in A*

返回如下代码:

  int manhattanDistanceSum = 0;
for (int x = 0; x < N; x++) // x-dimension, traversing rows (i)
    for (int y = 0; y < N; y++) { // y-dimension, traversing cols (j)
        int value = tiles[x][y]; // tiles array contains board elements
        if (value != 0) { // we don't compute MD for element 0
            int targetX = (value - 1) / N; // expected x-coordinate (row)
            int targetY = (value - 1) % N; // expected y-coordinate (col)
            int dx = x - targetX; // x-distance to expected coordinate
            int dy = y - targetY; // y-distance to expected coordinate
            manhattanDistanceSum += Math.abs(dx) + Math.abs(dy); 
        } 
    }

鉴于这个董事会和这个目标状态,这是我不明白的:

初始板:

 1,2,5
 3,0,4
 6,7,8

目标状态:

0,1,2
3,4,5
6,7,8

如果我输入 board[0][0] 的值,它的值为 1,恰好是 1 从其正确位置移开,我会得到以下结果:

 x = 0;
 y = 0;
 value = 1;
 targetX = (value -1)/3; // 0/3 = 0
 targetY = (value -1)%3 //0%3 = 0

 int dx = x - targetX; // 0 - 0
 int dy = y - targetY; // 0 - 0
 manhattanDistanceSum += Math.abs(dx) + Math.abs(dy); 

最终产生 0 + 0,这显然是不正确的,因为它应该返回 1 的值。

还有其他方法吗,例如:

  for(int i = 0; i < 3 i ++){
     for(int j =0; j < 3; j ++){
        int value = currentBoard[i][j];
        int goalValue = getLocationOfValueInGoalState(value);

       /* caluclate the value's X distance away from the returned goal state location   for said value, then do the same for the Y */





      }
   }

希望有人能理解我的问题,老实说,我现在有点困惑。

【问题讨论】:

  • 您的目标状态与第一个代码块所期望的目标状态不同。
  • 如果您使用调试器(或打印出中间值),您会发现问题。试试这样的循环,你会看到发生了什么: for (int value = 0; value

标签: java artificial-intelligence a-star heuristics


【解决方案1】:

您的目标状态与您正在查看的参考实现的目标状态之间存在细微差别。

对于参考实现,如果目标状态如下所示,它就可以工作:

1 2 3
4 5 6
7 8 0

在你的情况下,你想要曼哈顿距离:

0 1 2
3 4 5 
6 7 8

快速解决方法是简单地将您的目标状态重新定义为前者。

但是,如果后者是您真正想要的,则将 targetX/Y 更改为不从 value 中减去 1。

【讨论】:

  • 谢谢@Juser1167589 你能澄清一下为什么首先使用-1,我知道它是在对角有“空格”时使用的,但实际的英文描述是什么它有什么作用?
  • @chris edwards 这只是状态空间定义的问题。 - 1 出现在您正在查看的曼哈顿距离实现中,因为这两个板配置的顶部被认为是“目标状态”。您的实现将底部定义为“目标状态”,因此不需要 - 1 。请记住,状态空间,尤其是目标状态,是您定义启发式方法的依据。
【解决方案2】:

曼哈顿距离是定义为沿对角线移动棋子时距离增加的距离。如果可移动棋子在右上角,要将棋子移动到左下角,则不能直接沿对角线移动。您必须依次向左然后向下移动。增加的是曼哈顿距离。有趣的部分是洗牌算法。曼哈顿距离在数学中也称为出租车距离,http://en.wikipedia.org/wiki/Taxicab_geometry

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多