835. Image Overlap - medium
문제
Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.
(Note also that a translation does not include any kind of rotation.)
What is the largest possible overlap?
제한사항
- 1 <= A.length = A[0].length = B.length = B[0].length <= 30
- 0 <= A[i][j], B[i][j] <= 1
입출력 예
1
2
3
4
5
6
7
8
Input: A = [[1,1,0],
[0,1,0],
[0,1,0]]
B = [[0,0,0],
[0,1,1],
[0,0,1]]
Output: 3
Explanation: We slide A to right by 1 unit and down by 1 unit.
풀이
- Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
int m = A.size();
int n = A[0].size();
int answer = 0 ;
vector<vector<int>> count(2*m+1, vector<int>(2*n+1, 0));
for(auto i = 0 ; i < m ; ++i){
for(auto j = 0 ; j < n ; ++j){
if(A[i][j]){
for(auto t = 0 ; t < m ; ++t){
for(auto k = 0 ; k < n ; ++k){
if(B[t][k])
count[i - t + m][j - k + n] += 1;
}
}
}
}
}
for(auto& i : count){
for(auto& j : i){
answer = max(j, answer);
}
}
return answer;
}
};