簡體   English   中英

二進制搜索2D數組 - Java

[英]Binary Search 2D array - Java

我堅持以下問題:

給定大小為n 2的int二維矩陣mat ,其中n = 2 k ,搜索整數k。

矩陣的行和列已排序。

如果我們將矩陣分成四分之一,則每個季度也會進行排序。 例如,給定此矩陣:

-4 -2 5  9
 2  5 12 13
13 20 25 25
22 24 49 57  

如果我們把它分成幾個季度,我們可以看到第一季度的所有數字都等於或小於第二季度的數字。

為了獲得一個有效的算法,我想在二維上進行遞歸二進制搜索,但是它無法在前一個矩陣上搜索2

這是代碼:

public static boolean find(int[][] mat, int x){
    return find2(mat, x, 0, mat.length-1,0, mat.length-1);
}

private static boolean find2(int[][] mat, int x, int lorow, int hirow,int locol,int hicol){
    if(mat.length==0) return false;
    if(lorow>hirow || locol>hicol) return false;
    int midrow=(lorow+hirow)/2;
    int midcol=(locol+hicol)/2;
    if(mat[midrow][midcol] == x ) return true;
    else if(mat[midrow][midcol] < x) 
        return find2(mat,x,lorow,midrow,midcol+1,hicol) || find2(mat,x,midrow+1,hirow,locol,midcol) || find2(mat,x,midrow+1,hirow,midcol+1,hicol);
    else 
        return find2(mat,x,lorow,midrow,locol,midcol-1) || find2(mat,x,midrow,hirow,locol,midcol-1) || find2(mat,x,midrow+1,hirow,midcol+1,hicol);
}

請指教。

你的錯誤就在你的代碼中。

else 
    return find2(mat,x,lorow,midrow,locol,midcol-1) || find2(mat,x,midrow,hirow,locol,midcol-1) || find2(mat,x,midrow+1,hirow,midcol+1,hicol);

在前兩個函數中,您正在從搜索空間中刪除middle column 您需要包含它,因為元素可以出現在middle column 另一個錯誤是在最后一次調用find2(mat,x,midrow+1,hirow,midcol+1,hicol)

如果搜索元素小於中間元素,則應選擇中間元素top-left象限,並忽略bottom-right象限。 您錯誤地認為這里bottom-right象限過top-left象限。

相應地進行更改之后,else中的返回函數如下所示:

return find2(mat,x,lorow,midrow,locol,midcol) || find2(mat,x,lorow,midrow,midcol+1,hicol) ||find2(mat,x,midrow+1,hirow,locol,midcol);

這解決了問題,它返回-2true

更新的代碼:

private static boolean find2(int[][] mat, int x, int lorow, int hirow,int locol,int hicol){
    if(mat.length==0) return false;
    if(lorow>hirow || locol>hicol) return false;

    if(lorow==hirow && locol==hicol && mat[lorow][locol]!=x)
        return false;

    int midrow=(lorow+hirow)/2;
    int midcol=(locol+hicol)/2;

    if(mat[midrow][midcol] == x ) return true;
    else if(mat[midrow][midcol] < x) 
        return find2(mat,x,lorow,midrow,midcol+1,hicol) || find2(mat,x,midrow+1,hirow,locol,midcol) || find2(mat,x,midrow+1,hirow,midcol+1,hicol);
    else 
        return find2(mat,x,lorow,midrow,locol,midcol) || find2(mat,x,lorow,midrow,midcol+1,hicol) ||find2(mat,x,midrow+1,hirow,locol,midcol);
}

如果您的矩陣行和列已排序,您可以使用下面的代碼。

public int search(int mat[][], int n, int x) {
        int i = 0, j = n - 1;
        while (i < n && j >= 0) {
            if (mat[i][j] == x) {
                System.out.println("Found at" + i + j);
                return 1;
            }
            if (mat[i][j] > x)
                j--;
            else // if mat[i][j] < x
                i++;
        }

        System.out.println("not Found at");
        return 0;
    }

暫無
暫無

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

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