[英]Calculating Manhattan Distance within a 2d array
我正在编写一个程序来解决nxn 8难题。 我在测试程序时遇到的难题使我的Manhattan计算功能减少了2倍,遇到了困难。 最终将扩展为使用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
相同。
在您的示例中,这得到2乘以从0到8减去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);
}
而且不要扎根。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.