Two images A
and B
are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.
(Note also that a translation does not include any kind of rotation.)
What is the largest possible overlap?
Example 1:
Input: A = [[1,1,0], [0,1,0], [0,1,0]] B = [[0,0,0], [0,1,1], [0,0,1]] Output: 3 Explanation: We slide A to right by 1 unit and down by 1 unit.
Notes:
1 <= A.length = A[0].length = B.length = B[0].length <= 30
0 <= A[i][j], B[i][j] <= 1
思路:这个思路比较巧妙,用两个照片点的斜率,如果斜率相同,那么证明斜率相同的点,是可以shift过去的;跟SIFT的match一样;
class Solution {
public int largestOverlap(int[][] A, int[][] B) {
int rows = A.length;
int cols = A[0].length;
List<int[]> lista = new ArrayList<int[]>();
List<int[]> listb = new ArrayList<int[]>();
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(A[i][j] == 1) {
lista.add(new int[]{i, j});
}
if(B[i][j] == 1) {
listb.add(new int[]{i, j});
}
}
}
HashMap<String, Integer> map = new HashMap<>();
for(int[] pa: lista) {
for(int[] pb: listb) {
String slop = (pb[1] - pa[1]) + " " + (pb[0] - pa[0]);
map.put(slop, map.getOrDefault(slop, 0) + 1);
}
}
int max = 0;
for(Integer it: map.values()) {
max = Math.max(max, it);
}
return max;
}
}