Leetcode 85. Maximal Rectangle

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.

题意:找到一个矩阵中,值全部是1的最大矩形。

思路:这道题首先是肯定可以暴力求解的,以矩阵中每个是1元素为矩形的左上角,边长从2到n,往它的右下找出最大的矩形,但是这种时间复杂度应该是n的四次方。

看了discuss,思路是对每一行,把它上面的所有行往下做投影,比如上面的矩形会变成:
10100
20211
31322
40030
然后对每一行用84题Largest Rectangle in Histogram的方法求解最大矩阵。

public int maximalRectangle(boolean[][] matrix) {
    // Write your code here
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return 0;
    }
    
    int n = matrix.length;
    int m = matrix[0].length;
    int[][] height = new int[n][m];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (i == 0) {
                height[i][j] = matrix[i][j] ? 1 : 0;
            } else {
                height[i][j] = matrix[i][j] ? 1 + height[i-1][j] : 0;
            }
        }
    }
    
    int res = 0;
    for (int i = 0; i < n; i++) {
        Stack<Integer> stack = new Stack<Integer>();
        for (int j = 0; j <= m; j++) {
            int nowHeight = j == m ? -1 : height[i][j];
            while (!stack.isEmpty() && height[i][stack.peek()] >= nowHeight) {
                int h = height[i][stack.pop()];
                int w = stack.isEmpty() ? j : j - stack.peek() - 1;
                res = Math.max(res, h*w);
            }
            stack.push(j);
        }
    }
    
    return res;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/ff037346443c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞