簡體   English   中英

查找2D陣列中最接近的非零單元格

[英]Finding the closest non-zero cell in a 2D Array

我有一個二維的布爾數組。 我正在嘗試找到一個算法來遍歷這個數組並創建一個新的int數組,它打印出每個單元格中最接近的true。 因此,如果我們有一個布爾值,就像

0 1 0
0 0 0
0 0 1

然后我的int數組將是,

1 0 1
1 1 1
2 1 0

我試過遍歷數組並使用這個函數,

private static int checkClosest(boolean[][] check, int row, int col){
    int dist =0;
    int rowDist = 0;
    int colDist = 0;
    int diagDist = 0;
    for(int i=row; i< check.length;i++){
        if(check[i][col]){
           rowDist = (i-row);
            break;
        } 

    }
    for(int i= col; i<check[row].length; i++){
        if(check[row][i]){
           colDist = (i - col);
            break;
        } 

    }
    int count=0;
    for(int i= row, j= col; i < check[i].length; i++){
        if(check[i][j]){
           diagDist = count;
            break;
        }
        count++;
        j++;

    }
    dist = Math.max(rowDist, colDist);
    return Math.max(dist, diagDist);


}

但這不起作用。 有人可以用最佳方式幫助我做到這一點。

我認為你的方法是完全錯誤的。

那么這個函數找到由row,col指定的給定gell的關閉真實單元格的最小曼哈頓距離。 您所要做的就是遍歷整個2D陣列並找到最接近的陣列

private static int checkClosest(boolean[][] check, int row, int col){

    int minDist = 1000;    //Some really high value

    for(int i=0; i < check.length; i++){
        for(int j=0; i < check[i].length; j++){
            if(check[i][j]){
                minDist = Math.min(minDist , Math.abs(row-i)+Math.abs(col-j));
            }
        }
    }

    return minDist;
}

肯定有更有效的方法來做到這一點,但我不想用這種方式壓倒你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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