85. 最大矩形
难度困难
给定一个仅包含 0
和 1
、大小为 rows x cols
的二维二进制矩阵,找出只包含 1
的最大矩形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 输出:6 解释:最大矩形如上图所示。
示例 2:
输入:matrix = [] 输出:0
示例 3:
输入:matrix = [["0"]] 输出:0
示例 4:
输入:matrix = [["1"]] 输出:1
示例 5:
输入:matrix = [["0","0"]] 输出:0
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: def max_a(heights): heights = [0] + heights + [0] res = 0 stack = [] for i in range(len(heights)): cur = heights[i] while stack and cur < heights[stack[-1]]: top =stack.pop() area = heights[top] * (i-stack[-1]-1) res = max(res,area) stack.append(i) return res n1 = len(matrix) n2 = len(matrix[0]) f_res = 0 heights = [0] * n2 for i in range(0,n1): for j in range(0,n2): if matrix[i][j] == '1': heights[j]+=1 else: heights[j] = 0 f_res = max(f_res,max_a(heights)) return f_res
class Solution { public: // !!!!不要传引用,主函数中 每层都会对hights 修改 int largestRectangleArea(vector<int> heights) { int res = 0; stack<int> stk; heights.insert(heights.begin(),0); heights.emplace_back(0); for(int i = 0; i < heights.size();i++) { while(!stk.empty() && heights[i] < heights[stk.top()]) { int top = stk.top(); stk.pop(); int w = i-stk.top()-1; int h = heights[top]; res = max(res,w*h); } stk.push(i); } return res; } int maximalRectangle(vector<vector<char>>& matrix) { int res = 0; vector<int> heights = vector<int>(matrix[0].size(),0); for(int i = 0; i< matrix.size();i++) { for(int j = 0;j < matrix[0].size();j++){ if (matrix[i][j]== '1') { heights[j]+=1; } else { heights[j] = 0; } } res = max(res,largestRectangleArea(heights)); } return res; } };
解法一 暴力破解
遍历每个点,求以这个点为矩阵右下角的所有矩阵面积。如下图的两个例子,橙色是当前遍历的点,然后虚线框圈出的矩阵是其中一个矩阵。
作者:windliang
链接:https://leetcode.cn/problems/maximal-rectangle/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-1-8/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。