tag:
- Hard;
question:
??Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
?["1","0","1","0","0"],
?["1","0","1","1","1"],
?["1","1","1","1","1"],
?["1","0","0","1","0"]
]
Output: 6
思路:
??此題是之前那道的Largest Rectangle in Histogram 的擴展,這道題的二維矩陣每一層向上都可以看做一個直方圖,輸入矩陣有多少行,就可以形成多少個直方圖,對每個直方圖都調(diào)用直方圖中最大的矩形 中的方法,就可以得到最大的矩形面積。那么這道題唯一要做的就是將每一層構(gòu)成直方圖,由于題目限定了輸入矩陣的字符只有 '0' 和 '1' 兩種,所以處理起來也相對簡單。方法是,對于每一個點,如果是‘0’,則賦0,如果是 ‘1’,就賦之前的height值加上1。具體參見代碼如下:
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int res = 0;
vector<int> height;
for (int i = 0; i < matrix.size(); ++i) {
height.resize(matrix[i].size());
for (int j = 0; j < matrix[i].size(); ++j) {
height[j] = matrix[i][j] == '0' ? 0 : (1 + height[j]);
}
res = max(res, largestRectangleArea(height));
}
return res;
}
int largestRectangleArea(vector<int> &height) {
int res = 0;
stack<int> s;
height.push_back(0);
for (int i = 0; i < height.size(); ++i) {
if (s.empty() || height[s.top()] <= height[i])
s.push(i);
else {
int tmp = s.top();
s.pop();
res = max(res, height[tmp] * (s.empty() ? i : (i - s.top() - 1)));
--i;
}
}
return res;
}
};
類似題目: