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

    Example

    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.

    Analyse: Let dp[i][j] represents the maximum side of a square whose right bottom element is matrix[i][j]. 

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

    Runtime: 124ms

     1 class Solution {
     2 public:
     3     /**
     4      * @param matrix: a matrix of 0 and 1
     5      * @return: an integer
     6      */
     7     int maxSquare(vector<vector<int> > &matrix) {
     8         // write your code here
     9         if (matrix.empty() || matrix[0].empty()) return 0;
    10         
    11         int m = matrix.size(), n = matrix[0].size();
    12         vector<vector<int> > dp(m, vector<int>(n, 0));
    13         
    14         int result = 0;
    15         // initialize the first row
    16         for (int i = 0; i < n; i++) {
    17             if (matrix[0][i]) {
    18                 dp[0][i] = 1;
    19                 result = 1;
    20             }
    21         }
    22         
    23         // initialize the first column
    24         for (int i = 0; i < m; i++) {
    25             if (matrix[i][0]) {
    26                 dp[i][0] = 1;
    27                 result = 1;
    28             }
    29         }
    30         
    31         // calculate the remaining part
    32         for (int i = 1; i < m; i++) {
    33             for (int j = 1; j < n; j++) {
    34                 if (matrix[i][j]) {
    35                     dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1;
    36                     result = max(result, dp[i][j]);
    37                 }
    38                 else dp[i][j] = 0;
    39             }
    40         }
    41         return result * result;
    42     }
    43 };
  • 相关阅读:
    本博客主题设置
    .NET开源类库Nini手册(INI、XML、注册表的配置应用)-中文翻译
    service层的@Autowired 与@Override
    ajax传值时各参数意义
    序列化+继承
    KMP
    SpringBoot启动过程:
    Web三层架构及MVC
    SpringBoot注解意义及作用
    Syntax error on token "{", { expected after this token相关的错误
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5848145.html
Copyright © 2011-2022 走看看