Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
The question requires only one rectangle.
The algorithm is to calculate the length of a line segment H [I] [j] that can be expanded to the left at each point. L [I] [j], position R [I] [j] that can be expanded to the right.
For point A, the length of the Red Arrow headers with A continuous upward direction of 1 is 4, H [4] [1] = 4. This Red Arrow expands to the left and right sides as a rectangle and can be moved to the leftmost position. L [4] [1] = 1, R [4] [1] = 2 (L included in the matrix, R not included ). The area of the rectangle corresponding to Vertex A is H * (R-L) = 4.
For point B, H [3] [2] = 3, L [3] [2] = 1, R [3] [2] = 4. The corresponding area H * (R-L) = 9. Traverse all vertices to obtain the largest area. Because only data of H, L, and R is used for calculation, one-dimensional arrays instead of two-dimensional arrays are used for calculation.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;"> public class Solution {public int maximalRectangle (char [] [] matrix) {if (matrix = null | matrix. length = 0) return 0; int m = matrix. length; int n = matrix [0]. length; int [] H = new int [n]; int [] L = new int [n]; int [] R = new int [n]; for (int I = 0; I <n; I ++) {L [I] = 0; H [I] = 0; R [I] = n ;} int res = 0; for (int I = 0; I <m; I ++) {int left = 0; int right = n; for (int j = 0; j <n; j ++) {if (matrix [I] [j] = '1') {H [j] ++; L [j] = Math. max (L [j], left) ;}else {H [j] = 0; L [j] = 0; R [j] = n; left = j + 1 ;}}for (int j = n-1; j> = 0; -- j) {if (matrix [I] [j] = '1') {R [j] = Math. min (R [j], right); res = Math. max (res, H [j] * (R [j]-L [j]);} else {right = j ;}} return res ;}}