You are given two binary matrices A
and B
of size N x N
, where 1
represents a pixel and 0
represents an empty space. We can translate one matrix over the other matrix and count the number of overlapping 1
s. Your task is to find the largest possible overlap between translating the images A
and B
.
N
?
To solve this problem, we can follow these steps:
B
over matrix A
.1
s.A
by padding with zeros on all sides to simplify overlap calculation.B
over A
and for each position, count the number of overlapping 1
s.Here is the implementation in C++:
#include <vector>
#include <algorithm>
using namespace std;
int countOverlap(const vector<vector<int>>& A, const vector<vector<int>>& B, int rowOffset, int colOffset) {
int N = A.size();
int overlapCount = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
int iB = i + rowOffset;
int jB = j + colOffset;
if (iB >= 0 && iB < N && jB >= 0 && jB < N && A[i][j] == 1 && B[iB][jB] == 1) {
overlapCount++;
}
}
}
return overlapCount;
}
int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
int N = A.size();
int maxOverlap = 0;
for (int rowOffset = -N + 1; rowOffset < N; ++rowOffset) {
for (int colOffset = -N + 1; colOffset < N; ++colOffset) {
maxOverlap = max(maxOverlap, max(countOverlap(A, B, rowOffset, colOffset),
countOverlap(B, A, rowOffset, colOffset)));
}
}
return maxOverlap;
}
countOverlap
involves iterating through all N x N
elements. This takes O(N^2) time.Combining both, the total time complexity is O(N^4)
, which is feasible given the constraint that ( N \leq 30 ).
This approach ensures that we cover all possible translations and find the maximum overlap efficiently within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?