LeetCode-85. Maximal Rectangle

本文介绍了一种寻找二维矩阵中只包含1的最大矩形面积的算法。通过将每一行视为直方图,利用一维最大直方块面积的计算方法,并结合动态规划思想,最终求得最大矩形面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路

利用LeetCode-84. Largest Rectangle in Histogram的结果,把每一行的每一列元素都当做一个直方块,计算n次最大直方块面积,找出其中最大值,n为题目中二维数组的行数。

难点

如何确定当前行的每一列直方块高度,使用以下策略:

  • 将每列的高度初始化为0
  • 当前元素为1,则在原先的高度上加1
  • 当前元素为0,则重置为0

注意:官网上的测试案例有空数组,所以第一行要加上对它的判断。
此题还有使用动态规划的解法,具体见下方连接。

https://www.cnblogs.com/lupx/archive/2015/10/20/leetcode-85.html

Java实现

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0||matrix[0].length==0)
            return 0;
        int res=0;
        int row=matrix.length;
        int col=matrix[0].length;
        int[] heights=new int[col];
        for(int i=0;i<col;++i)
            heights[i]=0;
        for(int i=0;i<row;++i)
        {
            for(int j=0;j<col;++j)
            {
                if(matrix[i][j]=='0')
                    heights[j]=0;
                else
                    heights[j]+=1;
            }
            int maxArea=largestRectangleArea(heights);
            if(res<maxArea)
                res=maxArea;
        }
        return res;
    }
    public int largestRectangleArea(int[] heights) {  
        Stack<Integer> s=new Stack<>();  
        int maxArea=0;  
        int currentMaxArea=0;  
        int tp=0;  
        int i=0;  
        while(i<heights.length)  
        {  
            if(s.empty()||heights[s.peek()]<=heights[i])  
            {  
                s.push(i++);  
            }  
            else  
            {  
                tp=s.peek();  
                s.pop();  
                currentMaxArea=heights[tp]*(s.empty()?i:(i-s.peek()-1));  
                if(currentMaxArea>maxArea)  
                    maxArea=currentMaxArea;  
            }  
        }  
        while(!s.empty())  
        {  
            tp=s.peek();  
            s.pop();  
            currentMaxArea=heights[tp]*(s.empty()?i:(i-s.peek()-1));  
            if(currentMaxArea>maxArea)  
                maxArea=currentMaxArea;  
        }  
        return maxArea; 
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值