簡體   English   中英

計算二維數組中的曼哈頓距離

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM