题目如下:
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的基础上,就很容易解决了。
逐行遍历矩阵,将矩阵的第0~0行视为一个sub矩阵, 第0~1行视为一个sub矩阵,第0~2行视为一个sub矩阵, 第0~i行视为一个sub矩阵,对每个sub矩阵都运用Largest Rectangle in Histogram中的方法找寻最大的矩阵。
我的代码:
//116ms class Solution { public: int maximalHistogram(vector<int> height) { if (height.size() == 0) return 0; height.push_back(0); stack<int> stack; int index = 0; int max_sum = 0; int sum = 0; for (int i = 0; i < height.size(); ++i) { if (stack.empty() || height[i] > height[stack.top()]) { stack.push(i); } else { index = stack.top(); stack.pop(); sum = stack.empty() ? height[index] * i: height[index] * (i - stack.top() - 1); max_sum = sum > max_sum ? sum : max_sum; i--; } } return max_sum; } int maximalRectangle(vector<vector<char> > &matrix) { if (matrix.size() == 0) return 0; int rows = matrix.size(); int cols = matrix[0].size(); vector<int> height(cols, 0); for (int j = 0; j < cols; ++j) { //第0行 if (matrix[0][j] == '1') height[j] = 1; } int max_sum = maximalHistogram(height); int sum = 0; for (int i = 1; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if ( (height[j] >= 1) && (matrix[i][j] == '1')) height[j] +=1; else if (matrix[i][j] == '1') height[j] = 1; else height[j] = 0; }//构造每个0~i行构成的sub矩阵的直方图输入数据。 sum = maximalHistogram(height); max_sum = max_sum > sum ? max_sum : sum; } return max_sum; } };
后来参考了haoel的代码,发现上面这段代码可以写得更简洁一点,从而避免把第0行和剩下行分开进行赋值。
int maximalRectangle(vector<vector<char> > &matrix) { if (matrix.size()<=0 || matrix[0].size()<=0) return 0; int row = matrix.size(); int col = matrix[0].size(); vector< vector<int> > heights(row, vector<int> col); int maxArea = 0; for(int i=0; i<row; i++){ for(int j=0; j<col; j++) { if (matrix[i][j]=='1'){ heights[i][j] = (i==0 ? 1 : heights[i-1][j] + 1); //这行可以避免把第0行的赋值单独拿出来。 } } int area = largestRectangleArea(heights[i]); if (area > maxArea){ maxArea = area; } } return maxArea; }