Skip to content

Commit 669c786

Browse files
committed
Add solution #835
1 parent 12c8b48 commit 669c786

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,7 @@
642642
831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium|
643643
833|[Find And Replace in String](./0833-find-and-replace-in-string.js)|Medium|
644644
834|[Sum of Distances in Tree](./0834-sum-of-distances-in-tree.js)|Hard|
645+
835|[Image Overlap](./0835-image-overlap.js)|Medium|
645646
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
646647
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
647648
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|

solutions/0835-image-overlap.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* 835. Image Overlap
3+
* https://leetcode.com/problems/image-overlap/
4+
* Difficulty: Medium
5+
*
6+
* You are given two images, img1 and img2, represented as binary, square matrices of size n x n.
7+
* A binary matrix has only 0s and 1s as values.
8+
*
9+
* We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down
10+
* any number of units. We then place it on top of the other image. We can then calculate the
11+
* overlap by counting the number of positions that have a 1 in both images.
12+
*
13+
* Note also that a translation does not include any kind of rotation. Any 1 bits that are
14+
* translated outside of the matrix borders are erased.
15+
*
16+
* Return the largest possible overlap.
17+
*/
18+
19+
/**
20+
* @param {number[][]} img1
21+
* @param {number[][]} img2
22+
* @return {number}
23+
*/
24+
var largestOverlap = function(img1, img2) {
25+
const positions1 = [];
26+
const positions2 = [];
27+
28+
for (let i = 0; i < img1.length; i++) {
29+
for (let j = 0; j < img1.length; j++) {
30+
if (img1[i][j] === 1) {
31+
positions1.push([i, j]);
32+
}
33+
if (img2[i][j] === 1) {
34+
positions2.push([i, j]);
35+
}
36+
}
37+
}
38+
39+
if (positions1.length === 0 || positions2.length === 0) {
40+
return 0;
41+
}
42+
43+
const translations = new Map();
44+
let maxOverlap = 0;
45+
46+
for (const [r1, c1] of positions1) {
47+
for (const [r2, c2] of positions2) {
48+
const translation = `${r2 - r1},${c2 - c1}`;
49+
50+
if (!translations.has(translation)) {
51+
translations.set(translation, 0);
52+
}
53+
54+
translations.set(translation, translations.get(translation) + 1);
55+
maxOverlap = Math.max(maxOverlap, translations.get(translation));
56+
}
57+
}
58+
59+
return maxOverlap;
60+
};

0 commit comments

Comments
 (0)