Finding the maximum square sub-matrix with all equal elements in C++


In this problem, we are given a N*N matrix mat[]. Our task is finding the maximum square sub-matrix with all equal elements.

In this problem, we need to find the maximum size of a sub-matrix from the given matrix whose all elements are the same.

Let's take an example to understand the problem,

Input: mat[][] = {{1, 2, 1}, {1, 2, 2}, {2, 2, 2}}
Output: 2

Explanation

matrix a11, a12, a21, a22 is of size 2X2 and forms a sub-matrix with all equal elements.

Solution Approach

A simple solution to the problem is by traversing all the elements of the matrix and then checking for all sub-matrices that have the same element. The time complexity of the algorithm is O(n3) and each sub-matrix is created with time complexity of O(n2).

An Alternative method to solve the problem is using dynamic programming where we will store the largest size of the sub-matrix with all elements each till the position. For this we will be considering the neighbouring elements and then considering the longest matrix that satisfies the given condition. Let's formulate the width of any cell of the DP matrix.

If all the neighbours of the elements are the same, we will be increasing the values of the longest sub-matrix. In this case ,

$DP[i][j]\: =\: min(DP[i-1][j] , DP[i][j-1], DP[i-1][j-1]) + 1$

If this isn't the case,

DP[i][j] = 1

Example

Program to illustrate the working of our solution

#include<bits/stdc++.h>
#define n 4
#define m 4
using namespace std;
int findmaxSqMatSize(int mat[][m]){
   int DP[n][m];
   memset(DP, sizeof(DP), 0);
   int maxSqMatSize = 0;
   for (int i = 0 ; i < n ; i++){
      for (int j = 0 ; j < m ; j++){
         if (i == 0 || j == 0)
            DP[i][j] = 1;
         else{
            if (mat[i][j] == mat[i-1][j] && mat[i][j] == mat[i][j-1] && mat[i][j] == mat[i-1][j-1] )
               DP[i][j] = min(min(DP[i-1][j], DP[i][j-1]), DP[i-1][j-1] ) + 1;
            else DP[i][j] = 1;
         }
         maxSqMatSize = max(maxSqMatSize, DP[i][j]);
      }
   }
   return maxSqMatSize;
}
int main(){
   int mat[n][m] = { {2, 1, 4, 3},
   {5, 1, 1, 7},
   {1, 1, 1, 4},
   {9, 4, 6, 0}};
   cout<<"The maximum square sub-matrix with all equal elements is "<<findmaxSqMatSize(mat);
   return 0;
}

Output

The maximum square sub-matrix with all equal elements is 2

Updated on: 01-Feb-2022

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements