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.
1using System;
2class Program {
3 static void Main() {
4 int[,] img1 = { {1, 1, 0}, {0, 1, 0}, {0, 1, 0} };
5 int[,] img2 = { {0, 0, 0}, {0, 1, 1}, {0, 0, 1} };
6 Console.WriteLine("Max Overlap: " + LargestOverlap(img1, img2));
7 }
8
9 public static int LargestOverlap(int[,] img1, int[,] img2) {
10 int n = img1.GetLength(0);
11 int maxOverlap = 0;
12
13 for (int xShift = -n + 1; xShift < n; ++xShift) {
14 for (int yShift = -n + 1; yShift < n; ++yShift) {
15 maxOverlap = Math.Max(maxOverlap, OverlapCount(img1, img2, xShift, yShift));
16 }
17 }
18 return maxOverlap;
19 }
20
21 private static int OverlapCount(int[,] img1, int[,] img2, int xShift, int yShift) {
22 int n = img1.GetLength(0), count = 0;
23 for (int r = 0; r < n; ++r) {
24 for (int c = 0; c < n; ++c) {
25 if ((r + xShift >= 0 && r + xShift < n) && (c + yShift >= 0 && c + yShift < n)) {
26 count += img1[r, c] & img2[r + xShift, c + yShift];
27 }
28 }
29 }
30 return count;
31 }
32}
This C# implementation carries out a similar logic as other languages: by defining LargestOverlap
and OverlapCount
. The shifting occurs in ranges suitable to test all images superimpositions, and the main function outputs the max 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.