Sponsored
Sponsored
This solution involves shifting one image over another in all possible positions and counting how many ones overlap. By varying the horizontal and vertical shifts, and calculating overlaps with respect to the position of img2
, the solution finds the maximum overlap. This approach iterates over all possible translations, moving img1
relative to img2
and keeping track of the maximum overlap seen.
Time Complexity: O(n^4), where n is the size of the matrix, due to the two nested loops and a cross-sectional overlap check for each.
Space Complexity: O(1), since the solution uses constant space apart from input storage.
1#include <stdio.h>
2#include <stdlib.h>
3
4int overlapCount(int** img1, int** img2, int xShift, int yShift, int n) {
5 int count = 0;
6 for (int r = 0; r < n; ++r) {
7 for (int c = 0; c < n; ++c) {
8 if ((r + xShift >= 0 && r + xShift < n) && (c + yShift >= 0 && c + yShift < n)) {
9 count += img1[r][c] & img2[r + xShift][c + yShift];
10 }
11 }
12 }
13 return count;
14}
15
16int largestOverlap(int** img1, int** img2, int n) {
17 int maxOverlap = 0;
18 for (int xShift = -n + 1; xShift < n; ++xShift) {
19 for (int yShift = -n + 1; yShift < n; ++yShift) {
20 int overlap = overlapCount(img1, img2, xShift, yShift, n);
21 maxOverlap = maxOverlap > overlap ? maxOverlap : overlap;
22 }
23 }
24 return maxOverlap;
25}
26
27int main() {
28 int* img1[] = {(int[]){1, 1, 0}, (int[]){0, 1, 0}, (int[]){0, 1, 0}};
29 int* img2[] = {(int[]){0, 0, 0}, (int[]){0, 1, 1}, (int[]){0, 0, 1}};
30 int size = 3;
31 printf("Max Overlap: %d\n", largestOverlap(img1, img2, size));
32 return 0;
33}
The C code defines two functions, overlapCount
and largestOverlap
. overlapCount
calculates the number of overlapping 1s given a shift, while largestOverlap
tries all possible x and y shifts, keeps track of the maximum overlap, and returns the result. The main function initializes the images and prints the maximum overlap.
This solution uses the concept of convolution by considering the images as arrays of points. We tallied the number of overlapping 1s for each relative translation using convolution properties without directly shifting arrays and used efficient matrix operations to compute overlaps.
Time Complexity: O(n^4), as it traverses through each overlap position and checks all cells.
Space Complexity: O(n), due to the allocation of cumulative arrays.
1
For Java, arrays of coordinates store 1s efficiently. By translating shifts as strings for keys, a hashmap tracks overlaps, utilizing precise 1-position counting rather than relying on whole-matrix shifts.