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.
这题的思路完全来源Largest Rectangle in Histogram,不过要对原始数据做一个处理,把每行处理成直方图形式的数据。然后调用直方图的算法就可以了,所以你的先明白直方图最大面积计算方法。时间复杂度O(n^2)。
输入的矩阵
转换后的矩阵
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int>& height) { 4 int result=0; 5 height.push_back(0); 6 stack<int> mystack; 7 for(int i=0;i<height.size();i++) 8 { 9 if(mystack.empty() || height[mystack.top()]<=height[i]) 10 { 11 mystack.push(i); 12 } 13 else 14 { 15 int index = mystack.top(); 16 mystack.pop(); 17 int area = height[index]*(mystack.empty()?i:(i-mystack.top()-1)); 18 result = max(result,area); 19 i--; 20 } 21 } 22 return result; 23 } 24 25 int maximalRectangle(vector<vector<char>>& matrix) { 26 if(matrix.size()==0 || matrix[0].size()==0) return 0; 27 int result=0; 28 vector<vector<int>> histogram; 29 int rows = matrix.size(); 30 int cols = matrix[0].size(); 31 vector<int> height_row(cols,0); 32 for(int i=0;i<rows;i++) 33 { 34 for(int j=0;j<cols;j++) 35 { 36 if(matrix[i][j]=='1') 37 { 38 height_row[j]+=1; 39 } 40 else 41 { 42 height_row[j]=0; 43 } 44 } 45 histogram.push_back(height_row); 46 } 47 for(int i=0;i<rows;i++) 48 { 49 int maxArea = largestRectangleArea(histogram[i]); 50 result = maxArea>result?maxArea:result; 51 } 52 return result; 53 } 54 };
其实不需要把整个直方图矩阵得到后再计算,得到每行的直方图举证就可以计算了。
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int>& height) { 4 int result=0; 5 height.push_back(0); 6 stack<int> mystack; 7 for(int i=0;i<height.size();i++) 8 { 9 if(mystack.empty() || height[mystack.top()]<=height[i]) 10 { 11 mystack.push(i); 12 } 13 else 14 { 15 int index = mystack.top(); 16 mystack.pop(); 17 int area = height[index]*(mystack.empty()?i:(i-mystack.top()-1)); 18 result = max(result,area); 19 i--; 20 } 21 } 22 return result; 23 } 24 25 int maximalRectangle(vector<vector<char>>& matrix) { 26 if(matrix.size()==0 || matrix[0].size()==0) return 0; 27 int result=0; 28 int rows = matrix.size(); 29 int cols = matrix[0].size(); 30 vector<int> height_row(cols,0); 31 for(int i=0;i<rows;i++) 32 { 33 for(int j=0;j<cols;j++) 34 { 35 if(matrix[i][j]=='1') 36 { 37 height_row[j]+=1; 38 } 39 else 40 { 41 height_row[j]=0; 42 } 43 } 44 int maxArea = largestRectangleArea(height_row); 45 result = maxArea>result?maxArea:result; 46 } 47 return result; 48 } 49 };