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

前端 未结 5 1453
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  忘掉有多难
    2020-12-02 14:06

    The accepted answer by Nemo is nice but not fully correct:

    Thus, in linear time, we have identified a quadrant that must contain a local minimum, and we have cut n in half. Now just recurse.

    I am referring to "just recurse" bit. The problem is we cannot do that directly because on next iteration we might find a local minimum which is not a local minimum for original grid (x below means some arbitrary large numbers):

     x  x 39  x  x 50  x  x  x  x  x
     x  x 38  x  x 49  x  x  x  x  x
    37 36 33 34 35 48  x  x  x  x  x
     x  x 32  x  1 10  x  x  x  x  x
     x  x 31  x  x 47  x  x  x  x  x
    46 45 30 44 43 60 51 52 53 54 55
     x  x  2  x  x 56  x  x  x  x  x
     x  x  x  x  x 57  x  x  x  x  x
     x  x  x  x  x 58  x  x  x  x  x
     x  x  x  x  x 59  x  x  x  x  x
    

    At first iteration we find 10 to be a minimum of middle row and middle column. We go to the left (as 1 is less than 10). So our next iteration is on upper-left quadrant. But now minimum of middle row and column is going to be 31 (or 30 if quadrant's borders are considered to be part of it). You will then conclude that it is a local minimum. But it is not for the full grid.

    We can rectify this unfortunate defect in variety of ways. I solved it like this:

    At each iteration in addition to the grid itself we keep track of current minimum candidate (that is the 1 in the example above after first iteration; in the initial state we can say minimum candidate is plus infinity). We calculate minimum of middle row and column and compare it to minimum candidate. If the latter is smaller we recurse into the quadrant containing minimum candidate. Otherwise we forget previous candidate and only then check whether new middle row/column minimum is actually a local minimum. And if not then recurse as usual to whatever quadrant we slope down from it (and track new minimum candidate).

    Alternatively, you can modify the procedure as described in this presumably MIT lecture: at each iteration instead of looking at middle row/column you can look at middle row/column and grid boundary. Then the algorithm once again is correct.

    You choose which way you like.

提交回复
热议问题