public static int Maximalrectangle (char[][] matrix) { int rownum=matrix.length; if (rownum==0) return 0; int Columnnum =matrix[0].length; Int[][] Height=new int[rownum][columnnum+1]; int maxarea=0; for (int i=0;i<rownum;i++) {for (int j=0;j<columnnum;j++) {int k=i, height[i][j]=0; while (k>=0&&j< Columnnum) {if (matrix[k][j]== ' 1 ') height[i][j]++; else break; k--; } } height[i][columnnum]=-1; } stack<integer> stack=new stack<> (); for (int. i=0;i<rownum;i++) {for (int j=0;j<=columnnum;j++) {int a=height[i][j]; int b=stack.isempty ()? -1:stack.peek (); if (Stack.isempty () | | Height[i][j]>=height[i][stack.peek ()]) Stack.push (j); else {int temppop=stack.pop (); Maxarea=math.max (Maxarea, height[i][temppop]* (Stack.isempty ()? j:j-1-stack.peek ())); j--; }} stack.clear (); } return maxarea; }
Topic:
Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest rectangle containing all ones and return to its area.
In other words, to a 2-dimensional matrix of only 0 and 1, the maximum square area of which 1 can be composed
Solving:
This question can be regarded as the extension of the previous question (LeetCode84), the previous question input is an array, the value of each element of the array as the height of the rectangle, in this problem first to do a matrix processing, the elements of the matrix to calculate its height, after processing to get a matrix of each original matrix element height, Taking this matrix as input is similar to the previous question.
Code:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode85 Maximal Rectangle Java