835. Image Overlap

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]]))
                


猜你喜欢

转载自blog.csdn.net/zjucor/article/details/80298134