2D peak finding algorithm in O(n) worst case time?

前端 未结 3 1513
心在旅途
心在旅途 2020-12-23 15:18

I was doing this course on algorithms from MIT. In the very first lecture the professor presents the following problem:-

A peak in a 2D array is a value such that al

3条回答
  •  眼角桃花
    2020-12-23 15:58

    To see thata(n):

    Calculation step is in the picture

    To see algorithm implementation:

    1) start with either 1a) or 1b)

    1a) set left half, divider, right half.

    1b) set top half, divider, bottom half.

    2) Find global maximum on the divider. [theta n]

    3) Find the values of its neighbour. And record the largest node ever visited as the bestSeen node. [theta 1]

    # update the best we've seen so far based on this new maximum
    if bestSeen is None or problem.get(neighbor) > problem.get(bestSeen):
        bestSeen = neighbor
        if not trace is None: trace.setBestSeen(bestSeen)
    

    4) check if the global maximum is larger than the bestSeen and its neighbour. [theta 1]

    //Step 4 is the main key of why this algorithm works

    # return when we know we've found a peak
    if neighbor == bestLoc and problem.get(bestLoc) >= problem.get(bestSeen):
        if not trace is None: trace.foundPeak(bestLoc)
        return bestLoc
    

    5) If 4) is True, return the global maximum as 2-D peak.

    Else if this time did 1a), choose the half of BestSeen, go back to step 1b)

    Else, choose the half of BestSeen, go back to step 1a)


    To see visually why this algorithm works, it is like grabbing the greatest value side, keep reducing the boundaries and eventually get the BestSeen value.

    # Visualised simulation

    round1

    round2

    round3

    round4

    round5

    round6

    finally

    For this 10*10 matrix, we used only 6 steps to search for the 2-D peak, its quite convincing that it is indeed theta n


    By Falcon

提交回复
热议问题