Thursday, October 9, 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.Understand the problem:The problem itself is straight-forward. We can easily think of iterating all elements of the matrix, and for each element, we find the largest possible rectangles containing all ones. So we can expect that the time complexity would be O(m * n * m * n).A better Solution:We could maintain a dp matrix[m][n], where each row means the the height of 1's. Then scan each element of the matrix and update the height.At last, for each row, we know the histogram of each row, of which the value is the height of each element of that row. Then we can use the method Max rectangle of histogram to find out the largest rectangle. dp[i][j] - the maximal height for row i and column j.The initial value of the DP matrix is the first rowfor (int i = 0; i < n; i++) { dp[0][i] = matrix[0][i];}The transit function is:if (matrix[i][j]) == 0, dp[i][j] = 0;if (matrix[i][j]) == 1, dp[i][j] = dp[i - 1][j] + 1;The final state is to check the Math.max( max, maxRectangleHistogram(matrix[i]) )For example,The input matrix is:0 0 1 00 1 1 00 1 1 00 0 0 1So the DP matrix is0 0 1 0 10 1 2 0 20 2 3 0 40 0 0 1 1So the output is 4.Code (Java):