Finding the maximum square sub-matrix with all equal elements
Last Updated :
15 Apr, 2025
Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all equal elements i.e., all the elements in this submatrix must be same.
Constraints:
- 1 <= N <= 1000
- 0 <= Ai , j <= 109
Examples:
Input : a[][] = {{2, 3, 3},
{2, 3, 3},
{2, 2, 2}}
Output : 2
Explanation: A 2x2 matrix is formed from index
A0,1 to A1,2
Input : a[][] = {{9, 9, 9, 8},
{9, 9, 9, 6},
{9, 9, 9, 3},
{2, 2, 2, 2}
Output : 3
Explanation : A 3x3 matrix is formed from index
A0,0 to A2,2
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Method I ( Naive approach ):
We can easily find all the square submatrices in O(n3) time and check whether each submatrix contains equal elements or not in O(n2) time Which makes the total running time of the algorithm as O(n5).
Method II ( Dynamic Programming ):
For each cell (i, j), we store the largest value of K such that K x K is a submatrix with all equal elements and position of (i, j) being the bottom-right most element.
And DPi,j depends upon {DPi-1, j, DPi, j-1, DPi-1, j-1}
If Ai, j is equal to {Ai-1, j, Ai, j-1, Ai-1, j-1},
all the three values:
DPi, j = min(DPi-1, j, DPi, j-1, DPi-1, j-1) + 1
Else
DPi, j = 1 // Matrix Size 1
The answer would be the maximum of all DPi, j's
Below is the implementation of above steps.
C++
// C++ program to find maximum K such that K x K
// is a submatrix with equal elements.
#include<bits/stdc++.h>
#define Row 6
#define Col 6
using namespace std;
// Returns size of the largest square sub-matrix
// with all same elements.
int largestKSubmatrix(int a[][Col])
{
int dp[Row][Col];
memset(dp, sizeof(dp), 0);
int result = 0;
for (int i = 0 ; i < Row ; i++)
{
for (int j = 0 ; j < Col ; j++)
{
// If elements is at top row or first
// column, it wont form a square
// matrix's bottom-right
if (i == 0 || j == 0)
dp[i][j] = 1;
else
{
// Check if adjacent elements are equal
if (a[i][j] == a[i-1][j] &&
a[i][j] == a[i][j-1] &&
a[i][j] == a[i-1][j-1] )
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]),
dp[i-1][j-1] ) + 1;
// If not equal, then it will form a 1x1
// submatrix
else dp[i][j] = 1;
}
// Update result at each (i,j)
result = max(result, dp[i][j]);
}
}
return result;
}
// Driven Program
int main()
{
int a[Row][Col] = { 2, 2, 3, 3, 4, 4,
5, 5, 7, 7, 7, 4,
1, 2, 7, 7, 7, 4,
4, 4, 7, 7, 7, 4,
5, 5, 5, 1, 2, 7,
8, 7, 9, 4, 4, 4
};
cout << largestKSubmatrix(a) << endl;
return 0;
}
Java
// Java program to find maximum
// K such that K x K is a
// submatrix with equal elements.
import java.util.*;
import java.io.*;
class GFG
{
static int Row = 6, Col = 6;
// Returns size of the largest
// square sub-matrix with
// all same elements.
static int largestKSubmatrix(int [][]a)
{
int [][]dp = new int [Row][Col];
int result = 0;
for (int i = 0 ;
i < Row ; i++)
{
for (int j = 0 ;
j < Col ; j++)
{
// If elements is at top
// row or first column,
// it wont form a square
// matrix's bottom-right
if (i == 0 || j == 0)
dp[i][j] = 1;
else
{
// Check if adjacent
// elements are equal
if (a[i][j] == a[i - 1][j] &&
a[i][j] == a[i][j - 1] &&
a[i][j] == a[i - 1][j - 1])
{
dp[i][j] = (dp[i - 1][j] > dp[i][j - 1] &&
dp[i - 1][j] > dp[i - 1][j - 1] + 1) ?
dp[i - 1][j] :
(dp[i][j - 1] > dp[i - 1][j] &&
dp[i][j - 1] > dp[i - 1][j - 1] + 1) ?
dp[i][j - 1] :
dp[i - 1][j - 1] + 1;
}
// If not equal, then it
// will form a 1x1 submatrix
else dp[i][j] = 1;
}
// Update result at each (i,j)
result = result > dp[i][j] ?
result : dp[i][j];
}
}
return result;
}
// Driver code
public static void main(String[] args)
{
int [][]a = {{2, 2, 3, 3, 4, 4},
{5, 5, 7, 7, 7, 4},
{1, 2, 7, 7, 7, 4},
{4, 4, 7, 7, 7, 4},
{5, 5, 5, 1, 2, 7},
{8, 7, 9, 4, 4, 4}};
System.out.println(largestKSubmatrix(a));
}
}
// This code is contributed
// by ChitraNayal
C#
// C# program to find maximum
// K such that K x K is a
// submatrix with equal elements.
using System;
class GFG
{
static int Row = 6, Col = 6;
// Returns size of the
// largest square sub-matrix
// with all same elements.
static int largestKSubmatrix(int[,] a)
{
int[,] dp = new int [Row, Col];
int result = 0;
for (int i = 0 ; i < Row ; i++)
{
for (int j = 0 ;
j < Col ; j++)
{
// If elements is at top
// row or first column,
// it wont form a square
// matrix's bottom-right
if (i == 0 || j == 0)
dp[i, j] = 1;
else
{
// Check if adjacent
// elements are equal
if (a[i, j] == a[i - 1, j] &&
a[i, j] == a[i, j - 1] &&
a[i, j] == a[i - 1, j - 1])
{
dp[i, j] = (dp[i - 1, j] > dp[i, j - 1] &&
dp[i - 1, j] > dp[i - 1, j - 1] + 1) ?
dp[i - 1, j] :
(dp[i, j - 1] > dp[i - 1, j] &&
dp[i, j - 1] > dp[i - 1, j - 1] + 1) ?
dp[i, j - 1] :
dp[i - 1, j - 1] + 1;
}
// If not equal, then
// it will form a 1x1
// submatrix
else dp[i, j] = 1;
}
// Update result at each (i,j)
result = result > dp[i, j] ?
result : dp[i, j];
}
}
return result;
}
// Driver Code
public static void Main()
{
int[,] a = {{2, 2, 3, 3, 4, 4},
{5, 5, 7, 7, 7, 4},
{1, 2, 7, 7, 7, 4},
{4, 4, 7, 7, 7, 4},
{5, 5, 5, 1, 2, 7},
{8, 7, 9, 4, 4, 4}};
Console.Write(largestKSubmatrix(a));
}
}
// This code is contributed
// by ChitraNayal
Python 3
# Python 3 program to find
# maximum K such that K x K
# is a submatrix with equal
# elements.
Row = 6
Col = 6
# Returns size of the
# largest square sub-matrix
# with all same elements.
def largestKSubmatrix(a):
dp = [[0 for x in range(Row)]
for y in range(Col)]
result = 0
for i in range(Row ):
for j in range(Col):
# If elements is at top
# row or first column,
# it wont form a square
# matrix's bottom-right
if (i == 0 or j == 0):
dp[i][j] = 1
else:
# Check if adjacent
# elements are equal
if (a[i][j] == a[i - 1][j] and
a[i][j] == a[i][j - 1] and
a[i][j] == a[i - 1][j - 1]):
dp[i][j] = min(min(dp[i - 1][j],
dp[i][j - 1]),
dp[i - 1][j - 1] ) + 1
# If not equal, then
# it will form a 1x1
# submatrix
else:
dp[i][j] = 1
# Update result at each (i,j)
result = max(result, dp[i][j])
return result
# Driver Code
a = [[ 2, 2, 3, 3, 4, 4],
[ 5, 5, 7, 7, 7, 4],
[ 1, 2, 7, 7, 7, 4],
[ 4, 4, 7, 7, 7, 4],
[ 5, 5, 5, 1, 2, 7],
[ 8, 7, 9, 4, 4, 4]];
print(largestKSubmatrix(a))
# This code is contributed
# by ChitraNayal
PHP
<?php
// Java program to find maximum
// K such that K x K is a
// submatrix with equal elements.
$Row = 6;
$Col = 6;
// Returns size of the largest
// square sub-matrix with
// all same elements.
function largestKSubmatrix(&$a)
{
global $Row, $Col;
$result = 0;
for ($i = 0 ;
$i < $Row ; $i++)
{
for ($j = 0 ;
$j < $Col ; $j++)
{
// If elements is at
// top row or first
// column, it wont form
// a square matrix's
// bottom-right
if ($i == 0 || $j == 0)
$dp[$i][$j] = 1;
else
{
// Check if adjacent
// elements are equal
if ($a[$i][$j] == $a[$i - 1][$j] &&
$a[$i][$j] == $a[$i][$j - 1] &&
$a[$i][$j] == $a[$i - 1][$j - 1] )
$dp[$i][$j] = min(min($dp[$i - 1][$j],
$dp[$i][$j - 1]),
$dp[$i - 1][$j - 1] ) + 1;
// If not equal, then it
// will form a 1x1 submatrix
else $dp[$i][$j] = 1;
}
// Update result at each (i,j)
$result = max($result,
$dp[$i][$j]);
}
}
return $result;
}
// Driver Code
$a = array(array(2, 2, 3, 3, 4, 4),
array(5, 5, 7, 7, 7, 4),
array(1, 2, 7, 7, 7, 4),
array(4, 4, 7, 7, 7, 4),
array(5, 5, 5, 1, 2, 7),
array(8, 7, 9, 4, 4, 4));
echo largestKSubmatrix($a);
// This code is contributed
// by ChitraNayal
?>
JavaScript
<script>
// Javascript program to find maximum
// K such that K x K is a
// submatrix with equal elements.
let Row = 6, Col = 6;
// Returns size of the largest
// square sub-matrix with
// all same elements.
function largestKSubmatrix(a)
{
let dp = new Array(Row);
for(let i = 0; i < Row; i++)
{
dp[i] = new Array(Col);
for(let j = 0; j < Col; j++)
{
dp[i][j] = 0;
}
}
let result = 0;
for (let i = 0 ;
i < Row ; i++)
{
for (let j = 0 ;
j < Col ; j++)
{
// If elements is at top
// row or first column,
// it wont form a square
// matrix's bottom-right
if (i == 0 || j == 0)
dp[i][j] = 1;
else
{
// Check if adjacent
// elements are equal
if (a[i][j] == a[i - 1][j] &&
a[i][j] == a[i][j - 1] &&
a[i][j] == a[i - 1][j - 1])
{
dp[i][j] = (dp[i - 1][j] > dp[i][j - 1] &&
dp[i - 1][j] > dp[i - 1][j - 1] + 1) ?
dp[i - 1][j] :
(dp[i][j - 1] > dp[i - 1][j] &&
dp[i][j - 1] > dp[i - 1][j - 1] + 1) ?
dp[i][j - 1] :
dp[i - 1][j - 1] + 1;
}
// If not equal, then it
// will form a 1x1 submatrix
else dp[i][j] = 1;
}
// Update result at each (i,j)
result = result > dp[i][j] ?
result : dp[i][j];
}
}
return result;
}
// Driver code
let a = [[ 2, 2, 3, 3, 4, 4],
[ 5, 5, 7, 7, 7, 4],
[ 1, 2, 7, 7, 7, 4],
[ 4, 4, 7, 7, 7, 4],
[ 5, 5, 5, 1, 2, 7],
[ 8, 7, 9, 4, 4, 4]];
document.write(largestKSubmatrix(a));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity : O(Row * Col)
Auxiliary Space : O(Row * Col)
Similar Reads
Program to find the maximum element in a Matrix
Given an NxM matrix. The task is to find the maximum element in this matrix. Examples: Input: mat[4][4] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Output: 25 Input: mat[3][4] = {{9, 8, 7, 6}, {5, 4, 3, 2}, {1, 0, 12, 45}}; Output: 45 Approach: The idea is to traverse the mat
6 min read
Largest sub-matrix with all equal elements
Given a binary matrix of size N * M, the task is to find the largest area sub-matrix such that all elements in it are same i.e. either all are 0 or all are 1. Print the largest possible area of such matrix. Examples: Input: mat[][] = { {1, 1, 0, 1, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 0, 0, 1}, {1, 0, 0, 1,
15+ min read
Sum of all maximum frequency elements in Matrix
Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all maximum occurring elements in the given matrix. That is the sum of all such elements whose frequency is even in the matrix. Examples: Input : mat[] = {{1, 1, 1}, {2, 3, 3}, {4, 5, 3}} Output : 12 The max
6 min read
Find column with maximum sum in a Matrix
Given a N*N matrix. The task is to find the index of column with maximum sum. That is the column whose sum of elements are maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Column 5 has max sum 31 Input
7 min read
Find the row with maximum unique elements in given Matrix
Given a matrix arr[][] of size N*M The task is to find the index of the row that has the maximum unique elements. If there are multiple rows possible, return the minimum indexed row. Examples: Input: arr[][] = { {1, 2, 3, 4, 5}, {1, 2, 2, 4, 7}, {1, 3, 1, 3, 1} } Output: 0Explanation: Rows 0, 1
5 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2,
5 min read
Maximum size square sub-matrix with all 1s
Given a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s.Example:Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ]Output: 3Explanation: The maximum length of a
15+ min read
Maximum sum of elements from each row in the matrix
Given a matrix, find the maximum sum we can have by selecting just one element from every row. Condition is element selected from nth row must be strictly greater than element from (n-1)th row, else no element must be taken from row. Print the sum if possible else print -1. Examples : Input : 1 2 31
7 min read
Print all the sub diagonal elements of the given square matrix
Given a square matrix mat[][] of size n * n. The task is to print all the elements which lie on the sub-diagonal of the given matrix.Examples: Input: mat[][] = { {1, 2, 3}, {3, 3, 4, }, {2, 4, 6}} Output: 3 4Input: mat[][] = { {1, 2, 3, 4}, {3, 3, 4, 4}, {2, 4, 6, 3}, {1, 1, 1, 3}} Output: 3 4 1 Rec
7 min read
Find row with maximum sum in a Matrix
Given an N*N matrix. The task is to find the index of a row with the maximum sum. That is the row whose sum of elements is maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Row 3 has max sum 35 Input :
11 min read