[leetcode] 221. Maximal Square 解题报告

来源:互联网 发布:手机号小号软件 编辑:程序博客网 时间:2024/06/05 19:49

题目链接:https://leetcode.com/problems/maximal-square/

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

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.


思路:一道比较明显的动态规划题目。因为是要寻找一个正方形,所以就比较简单一些,借助一个辅助数组dp[][],dp[i][j]表示当前正方形的边长,并且其值由两种情况构成:

1. 如果matrix[i-1][j-1] = 1, 因为是正方形,则其值为min(dp[i-1][j-1],dp[i][j-1],dp[i-1][j])中的最小值加1,小正方形构成大正方形,状态转移方程即为:

dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;

2. 如果matrix[i-1][j-1] = 0,则dp[i][j] = 0;

时间复杂度为O(m*n),空间复杂度为O(m*n)

代码如下:

class Solution {public:    int maximalSquare(vector<vector<char>>& matrix) {        if(matrix.size()==0) return 0;        int row = matrix.size(), col = matrix[0].size(), ans = 0;        vector<vector<int>> dp(row+1, vector<int>(col+1, 0));        for(int i = 1; i <= row; i++)        {            for(int j = 1; j <= col; j++)            {                if(matrix[i-1][j-1]=='0') continue;                dp[i][j] = min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1])) + 1;                ans = max(ans, dp[i][j]);            }        }        return ans*ans;    }};



0 0