Image Overlap

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. 1 <= A.length = A[0].length = B.length = B[0].length <= 30
  2. 0 <= A[i][j], B[i][j] <= 1

Solution:

the key is to get a map of vector of coordinate diff -> count

class Solution {
    public int largestOverlap(int[][] A, int[][] B) {
        int n = A.length;
        List<int[]> A1 = new ArrayList();
        List<int[]> B1 = new ArrayList();
        for (int i = 0; i < A.length; i ++) {
            for (int j = 0; j < A.length; j ++) {
                if (A[i][j] == 1) {
                    A1.add(new int[]{i, j});
                }
                if (B[i][j] == 1) {
                    B1.add(new int[]{i, j});
                }
            }
        }
        Map<String, Integer> diffToCount = new HashMap();
        int max = 0;
        for (int i = 0; i < A1.size(); i ++) {
            for (int j = 0; j < B1.size(); j ++) {
                String key = (A1.get(i)[0] - B1.get(j)[0]) + ", " + (A1.get(i)[1] - B1.get(j)[1]);
                diffToCount.put(key, diffToCount.getOrDefault(key, 0) + 1);
                max = Math.max(max, diffToCount.get(key));
            }
        }
        return max;
    }
}