Find local minimum in n x n matrix in O(n) time

前端 未结 5 1448
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 13:16

So, this is not my home work question, but it is taken from an ungraded homework of the coursera course on algorithms and data structures (which is now complete).

Y

5条回答
  •  Happy的楠姐
    2020-12-02 14:16

    Well, this is how you divide and conquer it.

    1) Divide the n x n matrix into four n/2 x n/2 sub matrices.

    2) Keep dividing the sub matrices recursively until you end up with a 2 x 2 matrix

    3) Check if any element of 2 x 2 matrix is a local Minimum.

    Recurrence equation is : T(n) = 4*T(n/2) + O(1)

    4*T(n/2) for 4 n/2 x n/2 sub matrices and O(1) for checking if 2 x 2 sub matrix has a local minimum

    Master theorem says this is a O(n^2) worst case bound.

    But I think we can get a best case O(n) bound,

    (" RED ALERT! ---BEST CASE IS BOGUS, JUST BOGUS---RED ALERT!").

    if we exit the recursion stack after we have have found a local minimum in step 3.

    Pseudocode:

    private void FindlocalMin(matrix,rowIndex,colIndex,width){
        if(width == 1){ checkForLocalMinimum(matrix,rowIndex,colIndex); return;} //2x2 matrix
        FindlocalMin(matrix,rowIndex,colIndex,width/2);  
        FindlocalMin(matrix, (rowIndex + (width/2) + 1) ,colIndex,width/2);
        FindlocalMin(matrix,rowIndex, (colIndex + (width/2) + 1) ,width/2);
        FindlocalMin(matrix,(rowIndex + (width/2) + 1), (colIndex + (width/2) + 1) ,width/2);
    }
    
    private void checkForLocalMinimum(.........){
        if(found Local Minimum in 2x2 matrix){ exit recursion stack;} 
    }
    

    Here is a java implementation

提交回复
热议问题