835. Image Overlap

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

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

经过观察

(0,0)->(1,1)->(0,0)-(1,1)=(-1,-1)

(0,1)->(1,2)->(0,1)-(1,2)=(-1,-1)

(1,1)->(2,2)->(1,1)-(2,2)=(-1,-1)

从A对应到B是把整个矩阵的坐标x轴-1, y轴-1;

变相就是在求所有A矩阵1的点到B矩阵1的点的X轴和Y轴距离;

所有坐标的取值范围在(-N—N)之间;

实际上就是把一个一维求距离的easy的题换成了二维的题目;

class Solution {
public:
    int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
        int len=A.size();
        vector<vector<int>>m_map(2*len+1, vector<int>(2*len+1, 0));
        for(int i_A=0; i_A<len; ++i_A)
            for(int j_A=0; j_A<len; ++j_A)
                if(A[i_A][j_A]==1)
                    for(int i_B=0; i_B<len; ++i_B)
                        for(int j_B=0; j_B<len; ++j_B)
                            if(B[i_B][j_B]==1)++m_map[i_A-i_B+len][j_A-j_B+len];
        
        int ret=0;
        for(int i=0; i<m_map.size(); ++i)
            for(int j=0; j<m_map[i].size(); ++j)
                ret=max(ret, m_map[i][j]);
                    
        return ret;
    }
};

这题出的蛮不好的emmm

看没什么人写中文的解释所以我写下...QvQ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值