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 <iostream>
2#include <vector>
3using namespace std;
4
5int overlapCount(const vector<vector<int>>& img1, const vector<vector<int>>& img2, int xShift, int yShift) {
6 int n = img1.size(), count = 0;
7 for (int r = 0; r < n; ++r) {
8 for (int c = 0; c < n; ++c) {
9 if ((r + xShift >= 0 && r + xShift < n) && (c + yShift >= 0 && c + yShift < n)) {
10 count += img1[r][c] & img2[r + xShift][c + yShift];
11 }
12 }
13 }
14 return count;
15}
16
17int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {
18 int n = img1.size(), maxOverlap = 0;
19 for (int xShift = -n + 1; xShift < n; ++xShift) {
20 for (int yShift = -n + 1; yShift < n; ++yShift) {
21 int overlap = overlapCount(img1, img2, xShift, yShift);
22 maxOverlap = max(maxOverlap, overlap);
23 }
24 }
25 return maxOverlap;
26}
27
28int main() {
29 vector<vector<int>> img1 = {{1, 1, 0}, {0, 1, 0}, {0, 1, 0}};
30 vector<vector<int>> img2 = {{0, 0, 0}, {0, 1, 1}, {0, 0, 1}};
31 cout << "Max Overlap: " << largestOverlap(img1, img2) << endl;
32 return 0;
33}
The C++ solution uses vector
to handle matrices. It defines overlapCount
for overlap calculation with particular shifts and largestOverlap
to check all shifts. main
initializes matrices and outputs 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
The Python solution moves towards collecting shifted positions of 1s using tuples. By focusing solely on these keys in a defaultdict, tracking maximum deduced overlaps results in efficient calculation.