Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 6.
求矩阵中由1组成的最大子矩阵面积。
1、首先进行观察,发现如果直接遍历然后求出每一个点的最大矩阵明显是不对的,时间复杂度过高。
2、结合84题,发现这两道题十分类似,就题目中给出的例子可以仔细观察可以发现,最大子矩阵是以某一行作为底,然后用84题的方法,进行求解,所以先对这个矩阵进行转换,例子中的矩阵可以转换如下:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
转换之后:
1 0 1 0 0 2 0 2 1 1 3 1 3 2 2 4 0 0 3 0
然后对每一行进行最大矩阵面积求解。
public class Solution { public int maximalRectangle(char[][] matrix) { int len1 = matrix.length; if( len1 == 0) return 0; int len2 = matrix[0].length; if( len2 == 0) return 0; int result = 0; int[][] heights = new int[len1][len2]; for( int i = 0;i<len2;i++){ if( matrix[0][i] == '1') heights[0][i] = 1; } for( int i = 1;i < len1;i++){ for( int j = 0;j<len2;j++){ if( matrix[i][j] == '1') heights[i][j] = heights[i-1][j]+1; } } for( int i = 0;i<len1;i++){ result = Math.max(result,largestRectangleArea(heights[i])); } return result; } public int largestRectangleArea(int[] heights) { int len = heights.length; int result = 0; if( len == 0) return 0; int[] left = new int[len]; int[] right = new int[len]; left[0] = 0; for( int i = 1;i<len;i++){ int CurLeft = i-1; while( CurLeft >= 0 && heights[CurLeft]>=heights[i]){ CurLeft = left[CurLeft]-1; } left[i] = CurLeft+1; } right[len-1] = len-1; for( int i = len-2;i>=0;i--){ int CurRight = i+1; while( CurRight<len && heights[CurRight]>=heights[i]) CurRight = right[CurRight]+1; right[i] = CurRight-1; } for( int i = 0;i<len;i++){ result = Math.max(result,(right[i]-left[i]+1)*(heights[i])); } return result;} }