|
| 1 | +// User function Template for C++ |
| 2 | +class Solution { |
| 3 | + public: |
| 4 | + // Recursive function with memoization to find the size of the largest square ending at (i, j) |
| 5 | + int solve(vector<vector<int>>& mat, int i, int j, vector<vector<int>>& dp) { |
| 6 | + // Base condition: If out of bounds, return 0 |
| 7 | + if (i >= mat.size() || j >= mat[0].size()) return 0; |
| 8 | + |
| 9 | + // If the value is already computed, return it |
| 10 | + if (dp[i][j] != -1) return dp[i][j]; |
| 11 | + |
| 12 | + // If the current cell contains 0, it cannot form a square |
| 13 | + if (mat[i][j] == 0) return dp[i][j] = 0; |
| 14 | + |
| 15 | + // Recursive calls to calculate the size of squares in three directions: |
| 16 | + int right = solve(mat, i, j - 1, dp); // Square ending to the left |
| 17 | + int diagnol = solve(mat, i - 1, j, dp); // Square ending diagonally |
| 18 | + int down = solve(mat, i - 1, j - 1, dp); // Square ending above |
| 19 | + |
| 20 | + // Store the size of the square ending at (i, j) in the dp table |
| 21 | + return dp[i][j] = 1 + min({right, diagnol, down}); |
| 22 | + } |
| 23 | + |
| 24 | + // Main function to find the largest square submatrix with all 1s |
| 25 | + int maxSquare(vector<vector<int>>& mat) { |
| 26 | + int maxi = 0; // Variable to store the maximum square size |
| 27 | + int n = mat.size(); |
| 28 | + int m = mat[0].size(); |
| 29 | + |
| 30 | + // Create a memoization table and initialize it with -1 |
| 31 | + vector<vector<int>> dp(n, vector<int>(m, -1)); |
| 32 | + |
| 33 | + // Iterate through the matrix and calculate the largest square ending at each cell |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + for (int j = 0; j < m; j++) { |
| 36 | + maxi = max(maxi, solve(mat, i, j, dp)); // Update the maximum square size |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return maxi; // Return the maximum square size |
| 41 | + } |
| 42 | +}; |
0 commit comments