Leetcode 221 Solution

This article provides solution to leetcode question 221 (maximal-square)

https://leetcode.com/problems/maximal-square

Solution

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m = matrix.size();

        if (m == 0)
            return 0;

        int n = matrix[0].size();

        vector<vector<int>> dp;

        for (int i = 0; i < m; i++)
            dp.push_back(vector<int>(n));

        dp[0][0] = matrix[0][0] - '0';
        int max_size = dp[0][0];

        for (int i = 0; i < m; i++)
        {
            dp[i][0] = matrix[i][0] - '0';
            max_size = max(max_size, dp[i][0]);
        }

        for (int j = 0; j < n; j++)
        {
            dp[0][j] = matrix[0][j] - '0';
            max_size = max(max_size, dp[0][j]);
        }

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

                max_size = max(max_size, dp[i][j]);
            }
        }

        return max_size * max_size;
    }
};