Find Maximum side length of square in a Matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a 2-D matrix mat[][] of size n, n being an odd number. Our task is to Find Maximum side length of a square in a Matrix.

Problem Description − We need to find the length of the square matrix whose perimeter values are the same and it shares the same center as the matrix.

Let’s take an example to understand the problem,

Input

mat[][] = {
   {2, 4, 6, 6, 5},
   {1, 7, 7, 7, 3},
   {5, 7, 0, 7, 1},
   {3, 7, 7, 7, 1},
   {2, 0, 1, 3, 2}
}

Output

3

Solution Approach

A simple solution to the problem is by finding the center element of the matrix as it is an odd matrix, the center element would be at index (n/2, n/2). After finding the center we will find all the 2D sub-matrices around it which will check if all its elements are the same.

The submatrix at index i away from the center will have an element of row (n/2 - 1) and (n/2 + 1) from index (n/2 - 1) to (n/2 + 1). Also elements of column (n/2 - 1) and (n/2 + 1) from index (n/2 - 1) to (n/2 + 1) are included at its perimeter. We need to check if the sub-matrix for any value of i from 0 to n/2 has all perimeter elements the same.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
#define n 5
using namespace std;
int findMaxSideSquare(int matrix[][n]) {
   int squareLen = 1;
   for (int i = 0; i < n / 2; i++) {
      int sideVal = matrix[i][i];
      bool isSquare = true;
      for (int j = i; j < n - i; j++) {
         if (matrix[i][j] != sideVal)
            isSquare = false;
         if (matrix[n - i - 1][j] != sideVal)
            isSquare = false;
         if (matrix[j][i] != sideVal)
            isSquare = false;
         if (matrix[j][n - i - 1] != sideVal)
            isSquare = false;
      }
      if (isSquare)
         squareLen = n - 2 * i;
   }
   return squareLen;
}
int main() {
   int mat[n][n] = {
      {2, 4, 6, 6, 5},
      {1, 7, 7, 7, 3},
      {5, 7, 0, 7, 1},
      {3, 7, 7, 7, 1},
      {2, 0, 1, 3, 2}
   };
   cout<<"The maximum side length of square in a Matrix is "<<findMaxSideSquare(mat);
   return 0;
}

Output

The maximum side length of square in a Matrix is 3
raja
Published on 12-Mar-2021 10:29:19
Advertisements