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.
classSolution {publicintlargestOverlap(int[][] A,int[][] B) {int rows =A.length, cols =A[0].length;List<int[]> la =newArrayList<>(), lb =newArrayList<>(); // two lists to save pixel coordinatesfor (int r =0; r < rows; r++)for (int c =0; c < cols; c++) {// save the pixel coordinatesif (A[r][c] ==1)la.add(newint[] { r, c });if (B[r][c] ==1)lb.add(newint[] { r, c }); }Map<String,Integer> map =newHashMap<>();// map to map the vector (from a pixel in A to a pixel in B) to its countfor (int[] pixelA : la)for (int[] pixelB : lb) {String s = (pixelA[0] - pixelB[0]) +" "+ (pixelA[1] - pixelB[1]); // get the vector from a pixel in A to a pixel in Bmap.put(s,map.getOrDefault(s,0) +1); // count the number of same vectors }int max =0;for (int count :map.values()) max =Math.max(max, count);return max; }}