maximal-rectangle

来源:互联网 发布:pinnacle软件 编辑:程序博客网 时间:2024/06/12 00:33

题目:

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

程序:

class Solution {public:    int maximalRectangle(vector<vector<char> > &matrix) {     if(matrix.size()==0)        return 0;    int cols = matrix[0].size();    int* hist = new int[cols]();         // 以某一行为起头对应该列的最大矩形(列连续1个数)    int max_ = 0;    for(int i=0; i<matrix.size(); i++)     {         for(int j=0; j<cols; j++)         {             if(matrix[i][j]=='1')                 hist[j] += 1;             else                 hist[j] = 0;         }        max_ = max(max_, maxRectInHistogram(hist, cols) );     }    delete [] hist;    hist = nullptr;    return max_; } int maxRectInHistogram(int hist[], int n){           int* arr = new int[n];// 申请一个额外的数组  以i为结尾的最大面积        arr[0] = hist[0];           int m = hist[0]; // 最大面积           for(int i=1; i<n; i++)           {                   arr[i] = hist[i];                int temp = hist[i];                for(int j=i-1; j>=0 && hist[j] > 0; j--)                {                    temp = min(temp,hist[j]);                    arr[i] = max(arr[i],temp*(i-j+1));                }                if(m < arr[i])                        m = arr[i];        }        delete [] arr;        arr = nullptr;        return m;   }};