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

Mat*_*att 3 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
}
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的示例:

 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
Run Code Online (Sandbox Code Playgroud)

我的汉明计算是正确的并返回 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
Run Code Online (Sandbox Code Playgroud)

bla*_*sel 5

错误在于距离的更新。

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

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

曼哈顿 - 正如维基词典所述,它是通过行距离加上列距离来计算的。

你的算法必须像(小心,前面的伪代码!)

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

并且不要取平方根。