[leetcode] 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.

https://oj.leetcode.com/problems/maximal-rectangle/

 

思路:转化成每一行求 Largest Rectangle in Histogram

import java.util.Stack;

public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0)
            return 0;

        int m = matrix.length;
        int n = matrix[0].length;
        int res = 0;

        for (int i = 0; i < m; i++) {
            int[] height = new int[n];
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == '1') {
                    height[j]++;
                    for (int k = i - 1; k >= 0; k--) {
                        if (matrix[k][j] == '1')
                            height[j]++;
                        else
                            break;
                    }
                }
            }
            res = Math.max(res, largestRectangleArea(height));
        }

        return res;

    }

    private int largestRectangleArea(int[] height) {
        Stack<Integer> stack = new Stack<Integer>();
        int maxArea = 0;
        for (int i = 0; i < height.length;) {
            if (stack.isEmpty() || height[i] >= height[stack.peek()]) {
                stack.push(i++);
            } else {
                int start = stack.pop();
                int width = stack.isEmpty() ? i : (i - stack.peek() - 1);
                maxArea = Math.max(maxArea, height[start] * width);
            }

        }

        while (!stack.isEmpty()) {
            int start = stack.pop();
            int width = stack.isEmpty() ? height.length : (height.length - stack.peek() - 1);
            maxArea = Math.max(maxArea, height[start] * width);
        }

        return maxArea;
    }

    public static void main(String[] args) {
        char[][] matrix = new char[][] { { '0', '0', '1', '0' }, { '0', '0', '0', '1' }, { '0', '1', '1', '1' },
                { '0', '0', '1', '1' } };
        System.out.println(new Solution().maximalRectangle(matrix));

    }
}
View Code

 

第二遍记录: 

 

参考:

http://blog.csdn.net/doc_sgl/article/details/11832965

 

posted @ 2014-06-30 00:09  jdflyfly  阅读(150)  评论(0编辑  收藏  举报