Peak Element in 2D array

An item is said to be a peak element when it is greater than or equal with all four neighbor of that element. The neighbor elements are the top, bottom, left and right elements. For this problem, we will consider some bounds. The diagonal elements are not checked as neighbor elements. More than one peak element may present in a matrix, and the peak element is not necessarily the largest element in the matrix.

Input and Output

Input:
A matrix of different numbers.
10  8  10  10
14 13  12  11
15  9  11  11
15  9  11  21
16 17  19  20

Output:
The peak element of the matrix.
Here the peak element is: 21

Algorithm

findMaxMid(rows, mid, max)

Input: Rows number of the matrix, mid row, a max element as an output argument.

Output: Update the max item and index of the max element.

Begin
   maxIndex := 0
   for all rows r in the matrix, do
      if max 

findPeakElement(rows, columns, mid)

Input − Row and column of the matrix, and mid row place.

Output − Peak element in the matrix.

Begin
   maxMid := 0
   maxMidIndex := findMaxMid(rows, mid, maxMid)

   if mid is first or last column, then
      return maxMid

   if maxMid>= item of previous and next row for mid column, then
      return maxMid

   if maxMid is less than its left element, then
      res := findPeakElement(rows, columns, mid – mid/2)
      return res

   if maxMid is less than its right element, then
      res := findPeakElement(rows, columns, mid + mid/2)
      return res
End

Example

#include
#define M 4
#define N 4
using namespace std;

intarr[M][N] = {
   {10, 8, 10, 10},
   {14, 13, 12, 11},
   {15, 9, 11, 21},
   {16, 17, 19, 20}
};

intfindMaxMid(int rows, int mid, int&max) {
   intmaxIndex = 0;

   for (int i = 0; i = arr[maxMidIndex][mid-1] &&maxMid>= arr[maxMidIndex][mid+1])
      return maxMid;

   if (maxMid

Output

The peak element is: 21
Updated on: 2020-06-16T09:33:16+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements