Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 835. Image Overlap

Rain Hu

835. Image Overlap


一、題目

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 bordered are erased.
Return the largest possible overlap.

Example 1:
overlap1

Example 2:

Example 3:

Constraints:

二、分析

三、解題

1. Bit Manipulation

// 計算 bit 為 1 的數目:O(1)
int count(int bit) {
    int cnt = 0;
    while (bit) {
        bit -= (bit & -bit);
        cnt++;
    }
    return cnt;
}
// 將 matrix 轉為 2 進制數字的 array:O(n^2)
vector<int> masking(vector<vector<int>>& img) {
    vector<int> res(img.size(), 0);
    for (int i = 0; i < img.size(); i++) {
        for (int j = 0; j < img[i].size(); j++) {
            if (img[i][j]) res[i] |= (1 << j);
        }
    }
    
    return res;
}
int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {
    int n = img1.size();
    if (n == 0) return 0;
    vector<int> mask1 = masking(img1);
    vector<int> mask2 = masking(img2);
    int res = 0;
    for (int v = -n+1; v < n; v++) {
        for (int h = 0; h < n; h++) {
            int cnt1 = 0;
            int cnt2 = 0;
            for (int i = 0; i < n; i++) {
                int bit1 = (i+v<0 || i+v>=n) ? 0 : mask1[i+v];   // bit 上下移,越界補 0
                int bit2 = mask2[i];
                cnt1 += count((bit1 >> h) & bit2);      // bit1 右移
                cnt2 += count((bit2 >> h) & bit1);      // bit2 右移(視為 bit1 左移)
            }
            res = max({res, cnt1, cnt2});
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[Leetcode] 13. Roman to Integer
Next
[LeetCode] 2653. Sliding Subarray Beauty