Imagine you have two binary images represented as square matrices filled with 0s and 1s. Your task is to find the maximum overlap between these images by sliding one image over the other.
You can translate (slide) one image in any direction - left, right, up, or down - by any number of units. Think of it like placing a transparent sheet with holes (1s represent holes, 0s represent solid areas) over another sheet, and counting how many holes align perfectly.
Key Rules:
- Only translation is allowed - no rotation
- Any 1s that slide outside the matrix boundaries are lost
- Overlap occurs when both images have a
1at the same position - Return the maximum possible overlap count
This problem tests your ability to work with 2D transformations and efficiently explore all possible alignments.
Input & Output
Visualization
Time & Space Complexity
k is the number of 1s in the matrices. We compare each 1 in A with each 1 in B
Store coordinates of all 1s and frequency map of offsets
Constraints
- n == img1.length == img1[i].length
- n == img2.length == img2[i].length
- 1 โค n โค 30
-
img1[i][j] is either
0or1 -
img2[i][j] is either
0or1