221. Maximal Square(Leetcode每日一题-2020.05.08)

Problem

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

Solution

dp(i, j) 是以 matrix(i - 1, j - 1) 为 右下角 的正方形的最大边长

下图辅助理解状态转移方程
221. Maximal Square(Leetcode每日一题-2020.05.08)_第1张图片

class Solution {
     
public:
    int maximalSquare(vector<vector<char>>& matrix) {
     
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int row_cnt = matrix.size();
        int col_cnt = matrix[0].size();

        vector<vector<int>> dp(row_cnt+1,vector<int>(col_cnt+1,0));

        int max_side = 0;
        for(int i = 0;i<row_cnt;++i)
        {
     
            for(int j = 0;j<col_cnt;++j)
            {
     
                if(matrix[i][j] == '1')
                {
     
                    dp[i+1][j+1] = min(min(dp[i+1][j],dp[i][j]),dp[i][j+1])+1;
                    max_side = max(dp[i+1][j+1],max_side);
                } 
            }
        }

        return max_side * max_side;

    }
};

你可能感兴趣的:(leetcode动态规划)