Find peak in matrix

By | February 11, 2015
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

This is eveolved from 1D problem – find local min.
I would say this is a interesting problem and hvae great solution. The definition of “local” is near elements, ans in same row or column.
There is junmin’s implementation, link , which is similar to mine. And another very clear material from mit, link.

  1. package weeklychallenge3;
  2. import java.util.Arrays;
  3. public class PeakInMatrix {
  4.     public static void main(String[] args) {
  5.         int[][] matrix = {
  6.                 { 9, 3, 5, 2, 4, 9, 8 },
  7.                 { 7, 2, 5, 1, 4, 0, 3 },
  8.                 { 9, 8, 2, 3, 4, 4, 8 },
  9.                 { 7, 6, 3, 1, 3, 2, 3 },
  10.                 { 9, 0, 6, 0, 4, 6, 4 },
  11.                 { 9, 7, 8, 0, 5, 3, 0 },
  12.                 { 2, 1, 2, 1, 1, 1, 1 }
  13.             };
  14.         int[] result = findPeakInMatrix(matrix);
  15.         System.out.println(Arrays.toString(result));
  16.     }
  17.     public static int[] findPeakInMatrix(int[][] matrix) {
  18.         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  19.             return null;
  20.         }
  21.         int leftCol = 0, rightCol = matrix[0].length, totalRow = matrix.length, totalCol = matrix[0].length;
  22.         int midCol = 0, maxIndex = 0;
  23.         while (leftCol <= rightCol) {
  24.             midCol = (leftCol + rightCol) >> 1;
  25.             maxIndex = 0;
  26.             for (int i = 1; i < totalRow; i++) {
  27.                 maxIndex = (matrix[i][midCol] > matrix[maxIndex][midCol]) ? i : maxIndex;
  28.             }
  29.             if (midCol – 1 >= 0    && matrix[maxIndex][midCol – 1] > matrix[maxIndex][midCol]) {
  30.                 rightCol = midCol;
  31.             } else if (midCol + 1 < totalCol && matrix[maxIndex][midCol + 1] > matrix[maxIndex][midCol]) {
  32.                 leftCol = midCol;
  33.             } else {
  34.                 break;
  35.             }
  36.         }
  37.         return new int[] { maxIndex, midCol };
  38.     }
  39. }