其他分享
首页 > 其他分享> > 【leetcode】221. Maximal Square

【leetcode】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.

Example 1:

Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4

    这道题如果用暴力法是很难oc的,leetcode上有两道类似的题目,分别是对于一个矩阵求最大的矩形或者求最大的正方形,求最大矩形是个hard题目,需要使用单调栈,而这题是medium。

   这题有个小trick就是利用动态规划求解,定义一个二维矩阵,dp[i][j]定义为包含该点的正方形的最大边长即可。

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m=matrix.size();
        int n=matrix[0].size();
        vector<vector<int>> dp(m+1,vector<int>(n+1,0));
        int res=0;
        for(int i=1;i<=m;++i){
            for(int j=1;j<=n;++j){
                if(matrix[i-1][j-1]=='0'){
                    dp[i][j]=0;
                }
                else{
                    dp[i][j]=1+min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]));//状态转移方程
                    res=max(res,dp[i][j]);
                }
                
            }
        }
        return res*res;
        
    }
};

标签:Maximal,Square,matrix,int,这题,vector,leetcode,dp,size
来源: https://www.cnblogs.com/aalan/p/15702788.html