zoukankan      html  css  js  c++  java
  • 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} , 令

    • (a_{ij}) 表示其往左连续 1 的个数,
    • (b_{ij}) 表示其往上连续 1 的个数,
    • (c_{ij}) 表示以其为右下角的全 1 的正方形的边长。

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

    (ans = max(c_{ij}))

    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;
      }
    };
    
  • 相关阅读:
    maven解析xml+测试test+注解
    MyBatis简单了解
    获取字符串中不重复的第一个字符
    整合ssm集成框架
    Git版本控制的原理
    git优点缺点(简单介绍)
    Maven生命周期
    Maven仓库分类
    maven常用命令
    myVision云服务商业数据分析解决方案
  • 原文地址:https://www.cnblogs.com/Forgenvueory/p/12851366.html
Copyright © 2011-2022 走看看