[leetcode] 835. Image Overlap

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)

We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.

(Note also that a translation does not include any kind of rotation.)

What is the largest possible overlap?

Example 1:

Input: A = [[1,1,0],
            [0,1,0],
            [0,1,0]]
       B = [[0,0,0],
            [0,1,1],
            [0,0,1]]
Output: 3
Explanation: We slide A to right by 1 unit and down by 1 unit.

Notes:

  1. 1 <= A.length = A[0].length = B.length = B[0].length <= 30
  2. 0 <= A[i][j], B[i][j] <= 1

分析

题目的意思是:给你image A和B,看通过怎样滑动能从A变为B,滑动缺少的部分补0。

假设A和B的索引范围都是[0,N*N-1]

  1. 遍历A,如果值为1,则把对应的坐标存到LA中。
  2. 遍历B,如果值为1,则把对应的坐标存到LB中。
  3. 遍历LA和LB,统计count[i-j],如果我们滑动使得A[i]覆盖B[i],我们可以获得1分。
  4. 遍历count,返回最大值即为所求。
  • 这道题的trick很多,如果理解核心就能做出来,我这里也无能为力,当作学习一下。

代码

class Solution {
public:
    int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
        vector<int> LA,LB;
        int N=A.size();
        unordered_map<int,int> count;
        for(int i=0;i<N*N;i++){
            if(A[i/N][i%N]==1){
                LA.push_back(i/N*100+i%N);
            }
            if(B[i/N][i%N]==1){
                LB.push_back(i/N*100+i%N);
            }
        }
        for(int i:LA){
            for(int j:LB){
                count[i-j]++;
            }
        }
        int res=0;
        for(auto it:count){
            res=max(res,it.second);
        }
        return res;
    }
};

参考文献

835. Image Overlap

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值