Find largest rectangle containing only zeros in an N×N binary matrix

前端 未结 8 2338
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:25

Given an NxN binary matrix (containing only 0\'s or 1\'s), how can we go about finding largest rectangle containing all 0\'s?

Example:

      I
    0          


        
8条回答
  •  余生分开走
    2020-11-22 06:59

    Solution with space complexity O(columns) [Can be modified to O(rows) also] and time complexity O(rows*columns)

    public int maximalRectangle(char[][] matrix) {
        int m = matrix.length;
        if (m == 0)
            return 0;
        int n = matrix[0].length;
        int maxArea = 0;
        int[] aux = new int[n];
        for (int i = 0; i < n; i++) {
            aux[i] = 0;
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                aux[j] = matrix[i][j] - '0' + aux[j];
                maxArea = Math.max(maxArea, maxAreaHist(aux));
            }
        }
        return maxArea;
    }
    
    public int maxAreaHist(int[] heights) {
        int n = heights.length;
        Stack stack = new Stack();
        stack.push(0);
        int maxRect = heights[0];
        int top = 0;
        int leftSideArea = 0;
        int rightSideArea = heights[0];
        for (int i = 1; i < n; i++) {
            if (stack.isEmpty() || heights[i] >= heights[stack.peek()]) {
                stack.push(i);
            } else {
                while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) {
                    top = stack.pop();
                    rightSideArea = heights[top] * (i - top);
                    leftSideArea = 0;
                    if (!stack.isEmpty()) {
                        leftSideArea = heights[top] * (top - stack.peek() - 1);
                    } else {
                        leftSideArea = heights[top] * top;
                    }
                    maxRect = Math.max(maxRect, leftSideArea + rightSideArea);
                }
                stack.push(i);
            }
        }
        while (!stack.isEmpty()) {
            top = stack.pop();
            rightSideArea = heights[top] * (n - top);
            leftSideArea = 0;
            if (!stack.isEmpty()) {
                leftSideArea = heights[top] * (top - stack.peek() - 1);
            } else {
                leftSideArea = heights[top] * top;
            }
            maxRect = Math.max(maxRect, leftSideArea + rightSideArea);
        }
        return maxRect;
    }
    

    But I get Time Limite exceeded excpetion when I try this on LeetCode. Is there any less complex solution?

提交回复
热议问题