Monday, May 26, 2014

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.

Solution:

We keep the number of following rows and cols with a '1'.

public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0)
            return 0;
        int[][] rows = new int[matrix.length][matrix[0].length];
        int[][] cols = new int[matrix.length][matrix[0].length];
        int maxArea = 0;
        for(int i =matrix.length-1; i>=0; i--)
        {
            for(int j= matrix[0].length-1; j>=0; j--)
            {
                if(matrix[i][j]=='0')
                {
                    rows[i][j] = 0;
                    cols[i][j] = 0;
                }
                else
                {
                    rows[i][j]= i+1<matrix.length ? rows[i+1][j]+1 : 1;
                    cols[i][j]= j+1<matrix[0].length ? cols[i][j+1]+1 : 1;
                    int area = cols[i][j];
                    int minCol = cols[i][j];
                    for(int k=1; k<rows[i][j]; k++)
                    {
                        minCol = minCol > cols[i+k][j] ?cols[i+k][j] : minCol;
                        area = area < minCol * (k+1) ? minCol * (k+1) : area;
                    }
                    maxArea = maxArea < area ? area : maxArea;
                }
            }
        }
        return maxArea;
    }
}

No comments :

Post a Comment