Find number of cavities in a matrix in C++

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 −

 4 5 6 7 1 5 4 5 6

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 12:39:31