Maximal Rectangle

本文介绍了一种求解二维矩阵中最大全1矩形面积的算法。通过构建高度矩阵并运用单调栈技巧来高效地计算出最大矩形的面积。文章详细展示了算法实现过程,并附带完整的Java代码。

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

public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null) {
            throw new IllegalArgumentException("");
        } 
        if (matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        int[][] heights = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < heights.length; i++) {
            for (int j = 0; j < heights[0].length; j++) {
                if (i == 0) {
                    heights[i][j] = matrix[i][j] == '1' ? 1 : 0;
                } else {
                    heights[i][j] = matrix[i][j] == '1' ? 1 : 0;
                    if (heights[i][j] != 0) {
                        heights[i][j] = heights[i][j] + heights[i - 1][j];
                    }
                }
            }
        }
        int maxArea = 0;
        int row = heights.length, column = heights[0].length;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (stack.isEmpty()) {
                    stack.push(j);
                } else {
                    while (!stack.isEmpty() && heights[i][j] < heights[i][stack.peek()]) {
                        int last_height = heights[i][stack.pop()];
                        if (!stack.isEmpty()) {
                            maxArea = Math.max(maxArea, (j - 1 - stack.peek())*last_height);
                        } else {
                            maxArea = Math.max(maxArea, (j)*last_height);
                        }
                    }
                    stack.push(j);
                }
            }
            while (!stack.isEmpty()) {
                int last_height = heights[i][stack.pop()];
                if (!stack.isEmpty()) {
                    maxArea = Math.max(maxArea, (column - 1 - stack.peek())*last_height);
                } else {
                    maxArea = Math.max(maxArea, (column)*last_height);
                }
            }
        }
        return maxArea;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值