Find number of cavities in a matrix in C++


Consider one matrix is given. We have to find the number of cavities in the matrix. One element is denoted as cavity when all other elements surrounding it is greater than the element. So if the matrix is like −

456
715
456

So the output is 1.

We simply check the surrounding elements and form the decision.

Example

#include<iostream>
#define MAX 100
using namespace std;
int numberOfCavities(int array[][MAX], int n) {
   int arr[n + 2][n + 2];
   int count = 0;
   for (int i = 0; i < n + 2; i++) {
      for (int j = 0; j < n + 2; j++) {
         if ((i == 0) || (j == 0) || (i == n + 1) || (j == n + 1))
            arr[i][j] = INT_MAX;
         else
            arr[i][j] = array[i - 1][j - 1];
      }
   }
   for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= n; j++) {
         if ((arr[i][j] < arr[i - 1][j]) && (arr[i][j] < arr[i + 1][j]) && (arr[i][j] < arr[i][j - 1])
            && (arr[i][j] < arr[i][j + 1]) && (arr[i][j] < arr[i - 1][j - 1]) && (arr[i][j] < arr[i + 1][j + 1])
            && (arr[i][j] < arr[i - 1][j + 1]) && (arr[i][j] < arr[i + 1][j - 1])) count++;
      }
   }
   return count;
}
int main() {
   int a[][MAX] = { { 4, 5, 6 }, { 7, 1, 5 }, { 4, 5, 6 }};
   int n = 3;
   cout << "Number of cavities: " << numberOfCavities(a, n);
}

Output

Number of cavities: 1

Updated on: 18-Dec-2019

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements