Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest rectangle containing all ones and return to its area.
Test instructions: To find the largest matrix in the 0,1 matrix, 1.
Idea: Borrowed the previous question, first we calculate the dp[i][j] in row I, when the column J column, at this time the number of consecutive 1, and then calculate each row, each column is equivalent to a histogram.
public class Solution {public int maximalrectangle (char[][] matrix) {int n = matrix.length; if (n = = 0) return 0; int m = matrix[0].length; if (M = = 0) return 0; int dp[][] = new int[n+1][m+1]; for (int i = 0; i < m; i++) if (matrix[0][i] = = ' 1 ') dp[0][i] = 1; for (int j = 0, J < m; J + +) for (int i = 1; i < n; i++) if (matrix[i][j] = = ' 1 ') dp[i][j] = Dp[i-1][j] + 1 ; int ans = 0; for (int i = 0; i < n; i++) {int tmp = Largestrectanglearea (Dp[i]); Ans = math.max (ans, TMP); } return ans; } public int Largestrectanglearea (int[] height) {stack<integer> Stack = new stack<integer> (); int i = 0; int ans = 0; int h[] = new int[height.length+1]; H = arrays.copyof (height, height.length+1); while (I < h.length) {if (Stack.isempty () | | h[stack.peek ()] <= h[i]) Stack.push (i++) ; else { int t = Stack.pop (); Ans = math.max (ans, h[t] * (Stack.isempty ()? I:i-Stack.peek ()-1)); }} return ans; } }
Leetcode Maximal Rectangle