-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaximalSquare.java
69 lines (63 loc) · 1.32 KB
/
MaximalSquare.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ProjectFiles;
public class MaximalSquare {
public static void main(String[] args) {
System.out.println(maximalSquare(new char[][]
{{'1','1','1','1'},
{'1','1','0','1'},
{'1','1','0','1'}}));
System.out.println(maximalSquare(new char[][]{{'1','0'},{'0', '1'}}));
}
public static int maximalSquare(char[][] matrix) {
if(matrix.length == 0){
return 0;
}
if(matrix.length == 1){
for(int i = 0; i < matrix[0].length; i++){
if(matrix[0][i] == '1')
return 1;
}
return 0;
}
int[][] dup = new int[matrix.length][matrix[0].length];
int result = 0;
for(int i = 0; i < matrix[0].length; i++){
dup[0][i] = matrix[0][i] - '0';
if(matrix[0][i] == '1')
result = 1;
}
for(int i = 0; i < matrix.length; i++){
dup[i][0] = matrix[i][0] - '0';
if(dup[i][0] == 1)
result = 1;
}
for(int i = 1; i < matrix.length; i++){
for(int j = 1; j < matrix[0].length; j++){
if(matrix[i][j] == '1'){
dup[i][j] = (min(dup[i-1][j], dup[i-1][j-1], dup[i][j-1]) ) + 1;
if(dup[i][j] > result){
result = dup[i][j];
}
}
}
}
return result*result;
}
private static int min(int a, int b, int c) {
if(a < b){
if(a<c){
return a;
}
else{
return c;
}
}
else{// b <= a
if(b<c){
return b;
}
else{
return c;
}
}
}
}