leetcode 85 最大矩阵

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

       此题是之前那道的 85 直方图中最大的矩形 的扩展,这道题的二维矩阵每一层向上都可以看做一个直方图,输入矩阵有多少行,就可以形成多少个直方图,对每个直方图都调用 直方图中最大的矩形 中的方法,就可以得到最大的矩形面积。

public int maximalRectangle(char[][] matrix) {
    if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
    int res = 0;
    int[] help = new int[matrix[0].length];
    for(int i = 0; i < matrix.lenght; i++){
        for(int j = 0; j < matrix[0].length; j++){
            help[j] = matrix[i][j] - '0' == 0 ? 0 : help[j] + 1;
        }
        res = Math.max(maxRecFromBottom(help), res);
    }
}
public int maxRecFromBottom(int[] help) {
    int res = 0;
    Stack<Integer> s = new Stack<>();
    for(int i = 0; i < help.length; i++){
        while(!s.isEmpty() && help[i] <= help[s.peek()]){
            int j = s.pop();
            int k = s.isEmpty() ? -1 : s.peek();
            int curArea = (i - k - 1) * help[j];
            res = Math.max(res, curArea);
        }
        s.push(i);
    }
    while(!s.isEmpty()){
        int j = s.pop();
        int k = s.isEmpty() ? -1 : s.peek();
        int curArea = (help.length - k - 1) * help[j];
        res = Math.max(res, curArea);
    }
    return res;
}

猜你喜欢

转载自blog.csdn.net/qq_43322057/article/details/84659778