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