// C# program to find out the maximum length // of a side of a square sub-matrix with all 1s. using System; class GfG { static int maxSquareRecur(int i, int j, int[, ] mat, int[] ans, int[, ] memo) { // Return 0 for invalid cells if (i < 0 || i == mat.GetLength(0) || j < 0 || j == mat.GetLength(1)) return 0; // If value is memoized, return value. if (memo[i, j] != -1) return memo[i, j]; // Find the side of square for right, bottom, // and diagonal cells. int right = maxSquareRecur(i, j + 1, mat, ans, memo); int down = maxSquareRecur(i + 1, j, mat, ans, memo); int diagonal = maxSquareRecur(i + 1, j + 1, mat, ans, memo); // If mat[i][j]==0, then square cannot // be formed. if (mat[i, j] == 0) return memo[i, j] = 0; // Side of square will be int val = 1 + Math.Min(right, Math.Min(down, diagonal)); ans[0] = Math.Max(ans[0], val); // Memoize the value and return it. return memo[i, j] = val; } static int maxSquare(int[, ] mat) { int n = mat.GetLength(0), m = mat.GetLength(1); int[] ans = { 0 }; // Create 2d array for memoization int[, ] memo = new int[n, m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) memo[i, j] = -1; maxSquareRecur(0, 0, mat, ans, memo); return ans[0]; } static void Main() { int[, ] 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 } }; Console.WriteLine(maxSquare(mat)); } }