LeetCode-85 Maximal Rectangle

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

思路:

 

       

如上图所示,我们以i行为底边,比如以第5行为底边,则每一列的高度为[2, 5, 4, 0];

问题可以转变为求面积最大的柱形区间,因而问题可以转化成Largest Rectangle in Histogram

我们需要计算以每一行为底边时的最大面积,当计算得到以最后一行为底边的最大面积时,即为问题的解。

代码如下:

public int maximalRectangle(char[][] matrix) {
        if(matrix == null || matrix.length == 0)
            return 0;
        int m = matrix.length;
        int n = matrix[0].length;
        int[] A = new int[n];
        int max = 0;
        for(int i=0; i<m; i++) {
            for(int j=0; j<n; j++) {
                A[j] = matrix[i][j] == '1' ? A[j] + 1 : 0;
            }
            max = Math.max(max, maxArea(A));
        }
        return max;
        
    }
    
    public int maxArea(int[] A) {
        Stack<Integer> stack = new Stack<Integer>();
        int current = 0;
        int max = 0;
        for(int i=0; i<=A.length;) {
            if(i == A.length) {
                current = 0;
            } else {
                current = A[i];
            }
            
            if(stack.isEmpty() || current > A[stack.peek()]) {
                stack.push(i);
                i++;
            } else {
                int height = A[stack.pop()];
                int length = stack.isEmpty() ? i : i - stack.peek() - 1;
                max = Math.max(max, height * length);
            }
        }
        return max;
    }

 

posted on 2015-03-18 20:16  linxiong1991  阅读(131)  评论(0编辑  收藏  举报

导航