題目
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
解題之法
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;
}
};
分析
此題是之前那道的 Largest Rectangle in Histogram 直方圖中最大的矩形 的擴展,這道題的二維矩陣每一層向上都可以看做一個直方圖碎紊,輸入矩陣有多少行,就可以形成多少個直方圖,對每個直方圖都調(diào)用 Largest Rectangle in Histogram 直方圖中最大的矩形 中的方法,就可以得到最大的矩形面積屈藐。
那么這道題唯一要做的就是將每一層構(gòu)成直方圖屯仗,由于題目限定了輸入矩陣的字符只有 '0' 和 '1' 兩種,所以處理起來也相對簡單芋膘。方法是,對于每一個點霸饲,如果是‘0’为朋,則賦0,如果是 ‘1’厚脉,就賦 之前的height值加上1习寸。