题目:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
给一个二维的二进制矩阵,只包含0和1,找出只包含1的最大矩形并且返回这个矩形的面积。
思路:
本题通过下图变换可以转换为求 :LeetCode OJ 之 Largest Rectangle in Histogram (直方图中的最大矩形) 。
转换后矩阵可以变成下图所示矩阵,求最大矩阵相当于对每一行求直方图的最大矩形面积。
代码:
class Solution { public : int maximalRectangle(vector<vector< char > > &matrix) { int result = 0; if (matrix.empty() || matrix[0].empty()) return result; int row = matrix.size(); int col = matrix[0].size(); vector<vector<int > > histogram(row , vector< int >(col,0)); for ( int i = 0 ; i < row ; i++) { for ( int j = 0 ; j < col ; j++) { if (i == 0) histogram[i][j] = (matrix[i][j] == '1' ? 1 : 0); else histogram[i][j] = (matrix[i][j] == '1' ? histogram[i-1][j] + 1 : 0); } } for ( int i = 0 ; i < row ; i++) { int tmp = largestRectangleArea(histogram[i]); result = max(result , tmp); } return result; } int largestRectangleArea(vector< int > &height) { stack<int > stk; height.push_back(0); int maxArea = 0 ; for ( int i = 0 ; i < height.size() ;) { if (stk.empty() || height[i] > height[stk.top()]) { stk.push(i); i++; } else { int index = stk.top(); stk.pop(); int tmp = height[index] * (stk.empty() ? i : i-stk.top()-1); maxArea = max(maxArea , tmp); } } return maxArea; } };