Problem
You are given two images, img1
and img2
, represented as binary, square matrices of size n x n
. A binary matrix has only 0
s and 1
s as values.
We translate one image however we choose by sliding all the 1
bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1
in both images.
Note also that a translation does not include any kind of rotation. Any 1
bits that are translated outside of the matrix borders are erased.
Return the largest possible overlap.
Examples
Example 1:
$$ img1 = \begin{matrix} 1 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 0 \end{matrix} \text{ | } img2 = \begin{matrix} 0 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{matrix} $$
|
|
$$ img1 = \begin{matrix} 1 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 0 \end{matrix} \implies \begin{matrix} 0 & 1 & 1 \\ 0 & 0 & 1 \\ 0 & 0 & 1 \end{matrix} \implies \begin{matrix} 0 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{matrix} $$
The number of positions that have a 1 in both images is 3 (shown in red).
$$ img1 = \begin{matrix} 0 & 0 & 0 \\ 0 & \colorbox{red} 1 & \colorbox{red} 1 \\ 0 & 0 & \colorbox{red} 1 \end{matrix} \text{ | } img2 = \begin{matrix} 0 & 0 & 0 \\ 0 & \colorbox{red} 1 & \colorbox{red} 1 \\ 0 & 0 & \colorbox{red} 1 \end{matrix} $$
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Brute Force Translation and Overlap Calculation
Here is the approach:
- Brute Force Translation:
- For each possible translation (
x_shift
,y_shift
), slideimg1
overimg2
and compute the number of overlapping1
bits. - The translation can range from
-n + 1
ton - 1
for bothx
andy
directions, ensuring we cover all possible relative positions of the two images.
- For each possible translation (
- Computing Overlaps:
- For each combination of
x_shift
andy_shift
, translateimg1
and count the number of overlapping1
s withimg2
. - Keep track of the maximum overlap observed.
- For each combination of
Code
|
|
|
|
Complexity
- Time:
O(n^4)
because the algorithm checks each possible translation (n^2
possibilities) and for each translation, it checksn^2
elements. - Space:
O(1)
, as we are using a fixed amount of extra space for tracking the maximum overlap and the current overlap count.