Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

221. Maximal Square 🌟🌟

Given an m x n binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Dynamic Programming

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix){
        int n = matrix.size(), m = matrix[0].size();
        if (n < 1) return 0;

        vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));

        int max_sq = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (matrix[i - 1][j - 1] == '1') {
                    dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
                    max_sq = max(max_sq, dp[i][j]);
                }
            }
        }

        return max_sq * max_sq;
    }
};

READ