1
-
2
-
3
1
/**
4
2
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle
5
3
* containing all ones and return its area.
6
4
*/
7
5
8
6
public class MaximalRectangle {
9
7
public int maximalRectangle (char [][] matrix ) {
10
- int row = matrix .length ;
11
- if (row == 0 )
8
+ int rows = matrix .length ;
9
+ if (rows == 0 )
12
10
return 0 ;
13
- int col = matrix [0 ].length ;
14
- int [][] map = new int [row ][col ];
15
- int area = 0 ;
16
- for (int i = 0 ; i < row ; i ++) {
17
- for (int j = 0 ; j < col ; j ++) {
18
- int prev = 0 ;
19
- if (i != 0 ) {
20
- prev = map [i - 1 ][j ];
21
- }
22
- if (matrix [i ][j ] == '1' ) {
23
- map [i ][j ] = prev + 1 ;
24
- } else {
25
- map [i ][j ] = prev ;
26
- }
11
+ int maxArea = 0 ;
12
+ int cols = matrix [0 ].length ;
13
+ int [][] map = new int [rows ][cols ];
14
+ for (int j = 0 ; j < cols ; j ++) {
15
+ map [0 ][j ] = matrix [0 ][j ] == '0' ? 0 : 1 ;
16
+ }
17
+ for (int i = 1 ; i < rows ; i ++) {
18
+ for (int j = 0 ; j < cols ; j ++) {
19
+ map [i ][j ] = matrix [i ][j ] == '0' ? map [i - 1 ][j ]
20
+ : map [i - 1 ][j ] + 1 ;
27
21
}
28
22
}
29
- for (int i = 0 ; i < row ; i ++) {
30
- for (int j = i ; j < row ; j ++) {
31
- int [] line = new int [col ];
32
- for (int k = 0 ; k < col ; k ++) {
33
- line [k ] = map [j ][k ] - map [i ][k ]
34
- + (matrix [i ][k ] == '0' ? 0 : 1 );
23
+ int [] row = new int [cols ];
24
+ for (int i = 0 ; i < rows ; i ++) {
25
+ for (int j = i ; j < rows ; j ++) {
26
+ for (int k = 0 ; k < cols ; k ++) {
27
+ row [k ] = map [j ][k ] - (i == 0 ? 0 : map [i - 1 ][k ]);
35
28
}
36
- int l = 0 ;
37
- int tmp = 0 ;
38
- for (int f = 0 ; f < col ; f ++) {
39
- if (line [f ] == j - i + 1 )
40
- tmp ++;
41
- else {
42
- if (tmp > l ) {
43
- l = tmp ;
44
- }
45
- tmp = 0 ;
29
+ int count = 0 ;
30
+ for (int k = 0 ; k < cols ; k ++) {
31
+ if (row [k ] == j - i + 1 ) {
32
+ maxArea = Math .max (maxArea , ++count * (j - i + 1 ));
33
+ } else {
34
+ maxArea = Math .max (maxArea , count * (j - i + 1 ));
35
+ count = 0 ;
46
36
}
47
37
}
48
- if (tmp > l ) {
49
- l = tmp ;
50
- }
51
- int s = (j - i + 1 ) * l ;
52
- if (s > area ) {
53
- area = s ;
54
- }
55
38
}
56
39
}
57
- return area ;
40
+ return maxArea ;
58
41
}
59
42
}
0 commit comments