Processing math: 100%

LeetCode 每日一题 221. 最大正方形

在一个由 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

对于 matrix_{i j} , 令

  • aij 表示其往左连续 1 的个数,
  • bij 表示其往上连续 1 的个数,
  • cij 表示以其为右下角的全 1 的正方形的边长。

c[i][j] = min(a[i][j], b[i][j], c[i - 1][j - 1] + 1) (matrix_{ij} = '1')。

ans=max(cij)

class Solution {
 public:
  int maximalSquare(vector<vector<char> >& matrix) {
    if(matrix.size() == 0)
      return 0;
    const int n = matrix.size();
    const int m = matrix[0].size();

    vector<vector<int> >a(n, vector<int>(m, 0)); // from left to right
    vector<vector<int> >b(n, vector<int>(m, 0)); // from up to down
    vector<vector<int> >c(n, vector<int>(m, 0));
    int ans(0);
    for(int i = 0; i < n; ++i) {
      for(int j = 0; j < m; ++j) {
        const char ch = matrix[i][j];
        a[i][j] = b[i][j] = c[i][j] = (ch == '1' ? 1 : 0);
        if(i && ch == '1')
          b[i][j] += b[i - 1][j];
        if(j && ch == '1')
          a[i][j] += a[i][j - 1];
        if(i && j && ch == '1')
          c[i][j] = min(min(a[i][j], b[i][j]), c[i - 1][j - 1] + 1);
        ans = max(ans, c[i][j]);
        //cout << c[i][j] << " ";
      }
      //cout << endl;
    }
    return ans * ans;
  }
};
posted @   菁芜  阅读(118)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
点击右上角即可分享
微信分享提示