leetcode 143: Maximal Rectangle (incomplete)

Maximal Rectangle

Total Accepted: 7242 Total Submissions: 33510

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

(incomplete)


public class Solution {
    public int maximalRectangle(char[][] matrix) {
            if(matrix==null || matrix.length==0) return 0;
        
        
	        int m = matrix.length;
	        int n = matrix[0].length;
	        int max = 0;
	        Pair[][] d = new Pair[m][n];
	        
	        
	        d[0][0] = (matrix[0][0] == '0') ? new Pair(0,0) : new Pair(1,1); 
	        if(matrix[0][0]=='1') max = 1;
	        
	        for(int i=1; i<m; i++) {
	        	if(matrix[i][0] == '1') {
	        		d[i][0] = new Pair( d[i-1][0].first + 1, 1 );
	        		max = max > d[i][0].product ? max : d[i][0].product;
	        	} else {
	        		d[i][0] = new Pair(0,0);
	        	}
	        }
	        
	        for(int i=1; i<n; i++) {
	        	if(matrix[0][i] == '1') {
	        		d[0][i] = new Pair( 1, d[0][i-1].first + 1 );
	        		max = max > d[0][i].product ? max : d[0][i].product;
	        	} else {
	        		d[0][i] = new Pair(0,0);
	        	}
	        }
	        
	        for(int i=1; i<m; i++) {
	        	for(int j=1; j<n; j++) {
	        		if(matrix[i][j]=='1') {
	        			int x = Math.min( d[i-1][j].first, d[i-1][j-1].first);
	        			int y = Math.min( d[i][j-1].second, d[i-1][j-1].second);
	        			d[i][j] = Math.max( (x+1)*(y+1), Math.max(d[i-1][j].first+1, d[i][j-1].second+1 ) );
	        			
	        			
	        			
	        			max = max > d[i][j].product ? max : d[i][j].product;
	        		} else d[i][j] = new Pair(0,0);
	        	}
	        }
	        
	        return max;
    }
    
	static class Pair{
	    int first;
	    int second;
	    int product;
	    public Pair(int first, int second) {
	        this.first = first;
	        this.second = second;
	        product = first*second;
	    }
	    
	    public Pair() {
	        this(0,0);
	    }
	    @Override
	    public String toString() {
	    	return "["+first+','+second+"]";

	    }
	}
}


你可能感兴趣的:(leetcode 143: Maximal Rectangle (incomplete))