// C# program to find the length // of longest possible square // submatrix with maximum AND // value from the given matrix using System; class GFG{ // Function to calculate and return // the length of square submatrix // with maximum AND value static int MAX_value(int [,]arr) { // Extract dimensions int row = arr.GetLength(0); int col = arr.GetLength(1); // Auxiliary array int [,]dp = new int[row, col]; // c: Stores the maximum // value in the matrix // p: Stores the number // of elements in the // submatrix having // maximum AND value int i = 0, j = 0; int c = arr[0, 0], p = 0; int d = row; // Iterate over the matrix // to fill the auxiliary // matrix for(i = 0; i < d; i++) { for(j = 0; j < d; j++) { // Find the max element in // the matrix side by side if (c < arr[i, j]) { c = arr[i, j]; } // Fill first row and // column with 1's if (i == 0 || j == 0) { dp[i, j] = 1; } else { // For every cell, check if the // elements at the left, top and // top left cells from the current // cell are equal or not if (arr[i - 1, j - 1] == arr[i, j] && arr[i - 1, j] == arr[i, j] && arr[i, j - 1] == arr[i, j]) { // Store the minimum possible // submatrix size these // elements are part of dp[i, j] = Math.Min(dp[i - 1, j - 1], Math.Min(dp[i - 1, j], dp[i, j - 1])) + 1; } else { // Store 1 otherwise dp[i, j] = 1; } } } } for(i = 0; i < d; i++) { for(j = 0; j < d; j++) { // Checking maximum value if (arr[i, j] == c) { // If the maximum AND // value occurs more // than once if (p < dp[i, j]) { // Update the maximum // size of submatrix p = dp[i, j]; } } } } // Final output return p * p; } // Driver code public static void Main(String[] args) { int [,]arr = { { 9, 9, 3, 3, 4, 4 }, { 9, 9, 7, 7, 7, 4 }, { 1, 2, 7, 7, 7, 4 }, { 4, 4, 7, 7, 7, 4 }, { 5, 5, 1, 1, 2, 7 }, { 2, 7, 1, 1, 4, 4 } }; Console.Write(MAX_value(arr) + "\n"); } } // This code is contributed by gauravrajput1