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
| class Solution {
/*
[[0,0,0,0,1],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
[[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[1,0,0,0,0]]
*/
public int largestOverlap(int[][] img1, int[][] img2) {
int n = img1.length;
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
max = Math.max(max, intersectRightBottom(i, j, img1, img2));
max = Math.max(max, intersectRightBottom(i, j, img2, img1));
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
max = Math.max(max, intersectLeftBottom(i, j, img1, img2));
max = Math.max(max, intersectLeftBottom(i, j, img2, img1));
}
}
return max;
}
int intersectLeftBottom(int row, int col, int[][] img1, int[][] img2) {
int count = 0;
int n = img1.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + row < n &&
j - col >= 0 &&
img2[i + row][j - col] == img1[i][j] &&
img1[i][j] == 1) {
count++;
}
}
}
return count;
}
int intersectRightBottom(int row, int col, int[][] img1, int[][] img2) {
int count = 0;
int n = img1.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + row < n &&
j + col < n &&
img2[i + row][j + col] == img1[i][j] &&
img1[i][j] == 1) {
count++;
}
}
}
return count;
}
}
|