The idea is to scan the matrix row by row. In this row, we calculate a histogram of 1's that are directly continuously above the row. Then we could solve the maximal area of histogram using "Largest Rectangle in Histogram". Then entire algorithm takes O(n^2) time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int largestRectangleArea(vector<int>& h) { | |
stack<int> s; | |
h.push_back(0); | |
int p=0; | |
int largest=0; | |
while(!(s.empty()&&p==h.size()-1)){ | |
if(s.empty()&&p!=h.size()-1){ | |
s.push(p); | |
p++; | |
continue; | |
} | |
while(h[s.top()]<h[p]){ | |
s.push(p); | |
p++; | |
} | |
int curTop=s.top(); | |
s.pop(); | |
int area; | |
if(s.empty()) | |
area=p*h[curTop]; | |
else | |
area=(p-s.top()-1)*h[curTop]; | |
largest=area>largest? area: largest; | |
} | |
return largest; | |
} | |
int maximalRectangle(vector<vector<char>>& m) { | |
if(m.empty()) | |
return 0; | |
int rows=m.size(); | |
int cols=m[0].size(); | |
vector<int> hist(cols, 0); | |
int largest=0; | |
for(int i=0; i<rows; i++){ | |
for(int j=0; j<cols; j++){ | |
hist[j]=m[i][j]=='0'? 0:hist[j]+1; | |
} | |
int area=largestRectangleArea(hist); | |
largest=area>largest? area:largest; | |
} | |
return largest; | |
} | |
}; |
No comments:
Post a Comment