LeetCode 835. Image Overlap 解题报告(python)

835. Image Overlap

  1. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值