Leetcode C++《热题 Hot 100-53》221. 最大正方形

Leetcode C++《热题 Hot 100-53》221. 最大正方形

  1. 题目

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:

输入:

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

输出: 4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 动态规划系列题目,很经典
  • dp[i][j] = min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j]) + 1 , condition is matrix[i][j] == 1
  • 时间复杂度和空间复杂度均为n^2
  1. 代码
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        //这个动态规划有点难,最大的正方形
        //dp[i][j]  = min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j]) + 1 , condition is  matrix[i][j] == 1
        int n =  matrix.size();
        if (n == 0)
            return 0;
        int m = matrix[0].size();
        int **dp = new int*[n];
        int res = 0;
        for (int i = 0; i < n; i++) {
            dp[i] = new int[m];
            if (matrix[i][0] == '1')
                dp[i][0] = 1;
            else
                dp[i][0] = 0;
            res = max(res, dp[i][0]);
        }
        for (int j = 0; j < m; j++) {
            if (matrix[0][j] == '1')
                dp[0][j] = 1;
            else
                dp[0][j] = 0;
            res = max(res, dp[0][j]);
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (matrix[i][j] == '0')
                    dp[i][j] = 0;
                else {
                    dp[i][j] = min (dp[i][j-1], min(dp[i-1][j-1], dp[i-1][j])) +1;
                }
                res = max(res, dp[i][j]);
            }
        }
        return res*res;
    }
};
发布了205 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104915808