Leetcode 835: Image Overlap

grid47
grid47
Exploring patterns and algorithms
Aug 15, 2024 6 min read

You are given two square binary matrices img1 and img2, both of size n x n. Each matrix consists of 0s and 1s. You are allowed to slide img1 over img2 in any direction (up, down, left, or right) without rotating the matrix. Your task is to find the maximum number of overlapping positions where both img1 and img2 have a 1 in the same position after performing a translation.
Problem
Approach
Steps
Complexity
Input: The input consists of two n x n binary matrices img1 and img2, both representing images with 0s and 1s.
Example: Input: img1 = [[1,0,0], [1,0,0], [0,0,0]], img2 = [[0,1,0], [0,1,0], [0,0,0]]
Constraints:
• 1 <= n <= 30
• img1[i][j] is either 0 or 1.
• img2[i][j] is either 0 or 1.
Output: The output is an integer representing the largest number of overlapping 1s after translating img1 over img2.
Example: Output: 2
Constraints:
• The largest overlap can be calculated as the maximum number of 1s overlapping in both matrices after translation.
Goal: The goal is to compute the maximum number of 1s that overlap after translating img1 over img2.
Steps:
• Step 1: Extract the positions of 1s in both img1 and img2.
• Step 2: For each possible translation (i.e., shifts in horizontal and vertical directions), calculate the number of overlapping 1s.
• Step 3: Return the maximum overlap found across all translations.
Goal: Ensure that the translation does not exceed the boundaries of the matrices.
Steps:
• Ensure that the translation does not result in positions going out of bounds.
Assumptions:
• The matrices img1 and img2 are always of the same size.
Input: Input: img1 = [[1,0,0], [1,0,0], [0,0,0]], img2 = [[0,1,0], [0,1,0], [0,0,0]]
Explanation: In this example, the translation that aligns the 1s in both images gives a maximum overlap of 2.

Input: Input: img1 = [[1,1,0], [0,1,0], [0,1,0]], img2 = [[0,0,0], [0,1,1], [0,0,1]]
Explanation: After translating img1 right and down by 1 unit, we obtain a maximum overlap of 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus