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 <= A_{i , j} <= 10^{9}

Examples:

Input : a[][] = {{2, 3, 3}, {2, 3, 3}, {2, 2, 2}} Output : 2 Explanation: A 2x2 matrix is formed from index A_{0,1}to A_{1,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 A_{0,0}to A_{2,2}

**Method I ( Naive approach )**

We can easily find all the square submatrices in O(n^{3}) time and check whether each submatrix contains equal elements or not in O(n^{2}) time Which makes the total running time of the algorithm as O(n^{5}).

**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 DP_{i,j} depends upon {DP_{i-1, j}, DP_{i, j-1}, DP_{i-1, j-1}}

If A_{i, j}is equal to {A_{i-1, j}, A_{i, j-1}, A_{i-1, j-1}}, all the three values: DP_{i, j}= min(DP_{i-1, j}, DP_{i, j-1}, DP_{i-1, j-1}) + 1 Else DP_{i, j}= 1 // Matrix Size 1 The answer would be the maximum of all DP_{i, j}'s

Below is C++ implementation of above steps.

// 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; }

Output:

3

Time Complexity : O(Row * Col)

Auxiliary Space : O(Row * Col)

This article is contributed by **Shubham Gupta**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.