java - 计算二维数组内的曼哈顿距离

标签 java distance a-star

我正在编写一个程序来解决 nxn 8 难题。我的曼哈顿计算函数与我正在测试我的程序的谜题相差两个,我遇到了困难。这最终将扩展到使用 A* 寻路算法,但我还没有做到这一点。

这是我的函数(基于棋盘的初始状态,不考虑到目前为止所采取的移动量):

// sum of Manhattan distances between blocks and goal
public int Manhattan()  // i don't think this is right yet - check with vince/thomas
{
    int distance = 0;

    // generate goal board
    int[][] goal = GoalBoard(N);

    // iterate through the blocks and check to see how far they are from where they should be in the goal array
    for(int row=0; row<N; row++){
        for(int column=0; column<N; column++){
            if(blocks[row][column] == 0)
                continue;
            else
                distance += Math.abs(blocks[row][column]) + Math.abs(goal[row][column]);
        }
    }

    distance = (int) Math.sqrt(distance);

    return distance; // temp
}

这是我正在研究的示例:

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

 initial          goal         Hamming = 5 + 0          Manhattan = 10 + 0

我的汉明计算是正确的并返回 5,但我的曼哈顿返回 8 而不是 10。我做错了什么?

这是我的程序的输出:

Size: 3
Initial Puzzle: 
 8  1   3   
 4  0   2   
 7  6   5   

Is goal board: false

Goal Array: 
 1  2   3   
 4  5   6   
 7  8   0   
Hamming: 5
Manhatten distance: 8
Inversions: 12
Solvable: true

最佳答案

错误在于距离的更新。

在编写 distance += Math.abs(blocks[row][column]) + Math.abs(goal[row][column]); 时,您将添加初始单元格的所有内容和目标。初始值和目标值中仅排除一个与初始值中 0 坐标相同的单元格。

在您的示例中,这给出了 0 到 8 的 2 倍总和减去 5。2 * 36 -8 = 64。然后你取8的平方。

曼哈顿 - 如Wiktionary所述通过行距离加上列距离来计算。

你的算法必须像这样锁定(注意,前面是伪代码!)

for (cell : cells) {
    goalCell = findGoalcell(cell.row, cell.col);
    distance += abs(cell.row - goalCell.row);
    distance += abs(cell.col - goalCell.col);
} 

并且不要取平方根。

关于java - 计算二维数组内的曼哈顿距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507074/

相关文章:

javascript - 找到 HTML 元素和浏览器(或窗口)边之间的距离

python - 将networkx图输入zss算法(树编辑距离)

distance - A*曼哈顿距离

javascript - 如何在 A* 图形搜索结果中拉直不需要的转弯?

artificial-intelligence - A* 在启发式仅可接受但不一致时重新打开

java - Spring Batch 多步骤与单步骤

java - 定时quartz任务执行时长

java - 如何从 jena fusioni 服务器获取 rdf 文件并将其初始化为 Apache Jena 中的 OntModel?

java - Java 中可用的最佳可调整大小字节缓冲区是什么?

javascript - 修改 Levenshtein 距离函数以计算两组 x-y 坐标之间的距离?