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 < matrix[i, mid], then          max = matrix[i, mid],          maxIndex := r    done    return maxIndex End

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<iostream> #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 < rows; i++) {    //find max element in the mid column       if (max <arr[i][mid]) {          max = arr[i][mid];          maxIndex = i;       }    }    return maxIndex; } intfindPeakElement(int rows, int columns, int mid) {    intmaxMid = 0;    intmaxMidIndex = findMaxMid(rows, mid, maxMid);    if (mid == 0 || mid == columns-1)    //for first and last column, the maxMid is maximum       return maxMid;    // If maxMid is also peak    if (maxMid>= arr[maxMidIndex][mid-1] &&maxMid>= arr[maxMidIndex][mid+1])       return maxMid;    if (maxMid<arr[maxMidIndex][mid-1])     // If maxMid is less than its left element       return findPeakElement(rows, columns, mid - mid/2);    return findPeakElement(rows, columns, mid+mid/2); } int main() {    int row = 4, col = 4;    cout<< "The peak element is: "<<findPeakElement(row, col, col/2); }

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