Leetcode - Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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 4.

[balabala] 此题是Maximal Rectangle的变形题,思路仍然是求解各行为底的直方图中的最大正方形面积然后取最大值。求解某一行为底的直方图中的最大正方形面积,要求全1区域的宽度 >= 高度。

    public int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[] h = new int[cols + 1];
        int max = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == '1')
                    h[j] += 1;
                else
                    h[j] = 0;
            }
            max = Math.max(max, getLargestSquare(h));
        }
        return max;
    }
    private int getLargestSquare(int[] h) {
        LinkedList<Integer> stack = new LinkedList<Integer>();
        int max = 0;
        int i = 0;
        while (i < h.length) {
            if (stack.isEmpty() || h[i] >= h[stack.peek()]) {
                stack.push(i++);
            } else {
                int currH = h[stack.pop()];
                while (!stack.isEmpty() && h[stack.peek()] == currH)
                    stack.pop();
                int width = stack.isEmpty() ? i : (i - stack.peek() - 1);
                if (width >= currH)
                    max = Math.max(max, currH * currH);
            }
        }
        return max;
    }

 

 

你可能感兴趣的:(LeetCode)