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