엔지니어 게시판
LeetCode 솔루션 분류

[10/27] 835. Image Overlap

컨텐츠 정보

본문

Medium
987358Add to ListShare

You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.

We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.

Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.

Return the largest possible overlap.

 

Example 1:

Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.

The number of positions that have a 1 in both images is 3 (shown in red).

Example 2:

Input: img1 = [[1]], img2 = [[1]]
Output: 1

Example 3:

Input: img1 = [[0]], img2 = [[0]]
Output: 0

 

Constraints:

  • n == img1.length == img1[i].length
  • n == img2.length == img2[i].length
  • 1 <= n <= 30
  • img1[i][j] is either 0 or 1.
  • img2[i][j] is either 0 or 1.
Accepted
77,323
Submissions
121,313
태그

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 1250 ms, faster than 46.20% of Python3 online submissions for Image Overlap.
Memory Usage: 14.7 MB, less than 43.86% of Python3 online submissions for Image Overlap.
from collections import defaultdict
class Solution:
    def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
        a = []
        b = []
        
        N = len(img1)
        
        for row in range(N):
            for col in range(N):
                if img1[row][col] == 1: a.append((row,col))
                if img2[row][col] == 1: b.append((row,col))
                    
        
        diff_dic = defaultdict(int)
        
        for point1 in a:
            for point2 in b:
                diff_dic[(point1[0]-point2[0], point1[1]-point2[1])] += 1
        
        return max(diff_dic.values()) if diff_dic.values() else 0
전체 409 / 7 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 674 명
  • 오늘 방문자 7,304 명
  • 어제 방문자 8,323 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,589 명
알림 0