835. Image Overlap
- Image Overlap python solution
题目描述
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中1到B中1的平移向量,那么出现次数最多的平移向量的频率,就是可重叠1的最大个数
class Solution:
def largestOverlap(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: int
"""
d=collections.defaultdict(int)
a=[]
b=[]
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j]==1:
a.append((i,j))
if B[i][j]==1:
b.append((i,j))
ans=0
for x in a:
for y in b:
t=(y[0]-x[0],y[1]-x[1])
d[t]+=1
ans=max(ans,d[t])
return ans
Reference
https://leetcode.com/problems/image-overlap/discuss/150504/Python-Easy-Logic
本文详细解析了LeetCode上835题“图像重叠”的解决方案,介绍了如何通过计算两幅二进制图像移动后重叠部分含有1的最大数量,利用平移向量统计的方法找到最优解。
561

被折叠的 条评论
为什么被折叠?



