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.

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

 

猜你喜欢

转载自hcx2013.iteye.com/blog/2225287
今日推荐