我正在编写一个程序来解决 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/