【leetcode】835. Image Overlap

题目如下:

解题思路:抛开移动的过程只看移动完成的结果,记图片左上角为顶点,正方形边长为board,要使得两个图片要有重叠,那么一定其中一张图片的顶点和另外一张图片的某一个点重合。假设图片A的顶点A(0,0)和图片B的其中一个点B(x,y)重合,那么A与B重合的区域就是A(0,0) -> A(board-x,board-y) ,B(x,y) -> B(board,board) ,计算A与B的重合部分中每个点都为1的个数就是A(0,0)与B(x,y)重合时候能得到的overlap。最后计算出B中所有点与A(0,0)重合和A中所有点与B(0,0)重合的overlap,求出最大值即可。

代码如下:

class Solution(object):
    def getOverlap(self,a,b,ax,ay):
        count = 0
        for i in range(ax,len(a)):
            for j in range(ay,len(a[i])):
                if a[i][j] == b[i-ax][j-ay] == 1:
                    count += 1
        return count

    def largestOverlap(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: int
        """
        res = 0
        board = len(A)
        for i in range(board):
            for j in range(board):
                res = max(res,self.getOverlap(A,B,i,j))
                res = max(res, self.getOverlap(B, A, i, j))
        return res

 

posted @ 2018-10-17 17:33  seyjs  阅读(906)  评论(2编辑  收藏  举报