zoukankan      html  css  js  c++  java
  • Maximal Rectangle

    Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

    Analyse: For each row, we can determine the all 1's height of each element. 

    Runtime: 28ms.

     1 class Solution {
     2 public:
     3     int maximalRectangle(vector<vector<char> >& matrix) {
     4         if(matrix.empty() || matrix[0].empty()) return 0;
     5         
     6         int row = matrix.size();
     7         int col = matrix[0].size();
     8         vector<vector<int> > bar(row, vector<int> (col, 0));
     9         for(int i = 0; i < row; i++){
    10             for(int j = 0; j < col; j++){
    11                 if(matrix[i][j] == '0') bar[i][j] = 0;
    12                 else bar[i][j] = (i == 0 ? 1 : bar[i - 1][j] + 1);
    13             }
    14         }
    15         
    16         int result = 0;
    17         for(int i = 0; i < row ; i++){
    18             result = max(result, largestRectangleArea(bar[i]));
    19         }
    20         return result;
    21     }
    22     int largestRectangleArea(vector<int>& height) {
    23         height.push_back(-1);
    24         stack<int> index;
    25         int i = 0, result = 0;
    26         while(i < height.size()){
    27             if(index.empty() || height[i] > height[index.top()])
    28                 index.push(i++);
    29             else{
    30                 int temp = index.top();
    31                 index.pop();
    32                 result = max(result, height[temp] * (index.empty() ? i :(i-index.top()-1)));
    33             }
    34         }
    35         return result;
    36     }
    37 };
  • 相关阅读:
    [BZOJ3202][SDOI2013]项链
    Educational Codeforces Round 50
    [agc23E]Inversions
    [CF1016G]Appropriate Team
    [CF765F]Souvenirs
    [Luogu3733][HAOI2017]八纵八横
    [Luogu4609][FJOI2016]建筑师
    [BZOJ2159]Crash 的文明世界
    【学习笔记】Nim积
    PKUWC2020游记
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4751778.html
Copyright © 2011-2022 走看看