835. Image Overlap

本文介绍了一种计算两个二进制矩阵通过平移达到的最大重叠区域数量的方法。通过统计不同平移距离出现的频率来找出最多重叠的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

Example 1:

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.

Notes: 

  1. 1 <= A.length = A[0].length = B.length = B[0].length <= 30
  2. 0 <= A[i][j], B[i][j] <= 1

思路:最开始想求出以每个为1的节点开始的一个唯一字符串表达,但是同一个联通区域的点都要单独遍历,而且还要再求个substring,

code写了一堆,不如直接求变换的距离,统计变换距离最多的答案就是了,其实2者复杂度是一样的,哎,感觉刷了那么久,思维还是没啥实质性的提升啊

def largestOverlap(self, A, B):
        N = len(A)
        LA = [(i, j) for i in xrange(N) for j in xrange(N) if A[i][j]]
        LB = [(i, j) for i in xrange(N) for j in xrange(N) if B[i][j]]
        c = collections.Counter((x1 - x2, y1 - y2) for x1, y1 in LA for x2, y2 in LB)
        return max(c.values() or [0])

最开始的code

class Solution(object):
    def largestOverlap(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: int
        """
        from collections import deque
        n = len(A)
        def getAllString(a):
            s = set()
            for i in range(n):
                for j in range(n):
                    if not a[i][j]: continue
                    q, qq = deque([tt for tt in range(j,n) if a[i][tt]]), deque()
#                    t = ['%d_%d'%(0,tt) for tt in range(n) if a[0][tt]]
                    t = []
                    k = i+1
                    while q:
                        while q:
                            jj = q.popleft()
                            t.append('%d_%d'%(k-i-1,jj-j))
                            if k<n and a[k][jj]: qq.append(jj)
                        if qq and qq[-1]+1<n and a[k][qq[-1]+1]: qq.append(qq[-1]+1)
                        q, qq = qq, q
                        k+=1
                        
                    s.add(' '.join(t))
            return s
        
        s1 = getAllString(A)
        s2 = getAllString(B)
        s = s1&s2
        return max([len(t) for t in s])
    
s=Solution()
print(s.largestOverlap(A = [[1,1,0],
            [0,1,0],
            [0,1,0]],
       B = [[0,0,0],
            [0,1,1],
            [0,0,1]]))
                


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值