[LeetCode 解题报告]221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

Method 1. 暴力法,

考虑第一行,1 0 1 0 0 , 则第一行高度为1,则里边最大有1*1的正方形;

考虑第一行和第二行,合并为一行 2 0 2 1 1, 高度为2,则里边最大有2*2的正方形,前提是序列中存在2个连续的2;

.....

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int res = 0;
        for (int i = 0; i < matrix.size(); i ++) {
            vector<int> v(matrix[i].size(), 0);
            for (int j = i; j < matrix.size(); j ++) {
                for (int k = 0; k < matrix[j].size(); k ++) {
                    if (matrix[j][k] == '1')
                        v[k] ++;
                }
                res = max(res, getSquareArea(v, j-i+1));
            }
        }
        return res;
    }
    
    int getSquareArea(vector<int>& v, int k) {
        int count = 0;
        for (int i = 0; i < v.size(); i ++) {
            if (v[i] != k)
                count = 0;
            else
                count ++;
            if (count == k)
                return k*k;
        }
        return 0;
    }
};

Method 2. dp;

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if (matrix.empty() || matrix[0].empty())
            return 0;
        
        int row = matrix.size(), col = matrix[0].size();
        vector<vector<int>> dp(row, vector<int>(col, 0));
        int res = 0;
        
        for (int i = 0; i < row; i ++) {
            for (int j = 0; j < col; j ++) {
                if (i == 0 || j == 0)
                    dp[i][j] = matrix[i][j] - '0';
                else if (matrix[i][j] == '1')
                    dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1;
                res = max (res, dp[i][j]);
            }
        }
        return res*res;
    }
};
发布了467 篇原创文章 · 获赞 40 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104195956