zoukankan      html  css  js  c++  java
  • LeetCode 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 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0
    

    Return 4.

    class Solution {
    public:
        int maximalSquare(vector<vector<char>>& matrix) {
            int rows = matrix.size();
            if (rows < 1) {
                return 0;
            }
            int cols = matrix[0].size();
            if (cols < 1) {
                return 0;
            }
            
            vector<int> dp0(cols + 1, 0);
            vector<int> dp1(cols + 1, 0);
            
            int dlen = 0;
            for (int i=1; i<=rows; i++) {
                for (int j=1; j<=cols; j++) {
                    if (matrix[i-1][j-1] == '0') {
                        dp1[j] = 0;
                    } else {
                        dp1[j] = min(dp1[j-1], min(dp0[j], dp0[j-1])) + 1;
                    }
                    dlen = max(dlen, dp1[j]);
                }
                swap(dp0, dp1);
            }
            return dlen * dlen;
        }
    };

    dp写起来爽,想起来不爽

  • 相关阅读:
    dmesg
    [转]df命令
    [转]linux /proc/cpuinfo 文件分析
    awk
    sed
    [转]进程间通信
    Bootstrap 树形列表与右键菜单
    Maven国内仓库
    《深入剖析Tomcat》源码
    Spring in Action学习笔记(2)
  • 原文地址:https://www.cnblogs.com/lailailai/p/4558376.html
Copyright © 2011-2022 走看看