835. Image Overlap
给予两个矩阵A和B,我们可以任意上下左右的位移该矩阵,判断经过任意次位移后可得的
最大重叠数(A[y][x] == B[y][x] == 1 我们说他重叠)。
https://assets.leetcode.com/uploads/2020/09/09/overlap1.jpg
Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.
https://assets.leetcode.com/uploads/2020/09/09/overlap_step1.jpg
The number of positions that have a 1 in both images is 3 (shown in red).
https://assets.leetcode.com/uploads/2020/09/09/overlap_step2.jpg
思路:
1.因为我想睡觉所以我们应该对两个矩阵使用暴力法
2.用-n+1~n-1表示左到右、上到下的位移,然后直接比较A和B位移过后是否都是1
3.统计完的sum取大的值
JavaCode:
class Solution {
public int largestOverlap(int[][] A, int[][] B) {
int n = A.length;
int res = 0;
for(int i = -n + 1; i < n; i++)
for(int j = -n + 1; j < n; j++) {
int sum = 0;
for(int x = 0; x < n; x++)
for(int y = 0; y < n; y++)
if(x + i >= 0 && x + i < n && y + j >= 0 && y + j < n)
sum += A[x + i][y + j] & B[x][y];
res = Math.max(res, sum);
}
return res;
}
}
晚安
https://i.imgur.com/nYPrAZB.png