# LeetCode #835: Image Overlap

By [Coder OP](https://paragraph.com/@coder-op) · 2022-11-06

---

Ok So, Lets start There are many solutions here but none of them have talked about the intuition. I will take you step by step with the complete Logic.

LOGIC :- Initially take all the 1's in both of the matrices into two different vectors. Or vector of pairs for our convinience as we are going to store the coordinates both x and y.

Now,

The main logic here is to simply map ! each of the 1's from first matrix to every 1 that is present in the other matrix.

![](https://storage.googleapis.com/papyrus_images/7f7c42649952c2128e85a693deed03877242fe514a36b569cd352779e4d7eb31.png)

Just do the same for all the other 1's in matrix1. And we keep track of overlapping that we get in all of these cases. The one with maximum overlapping is our answer.

    int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {
            int n=img1.size();
            vector<pair<int,int>>vp1,vp2;
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    if(img1[i][j]==1){
                        vp1.push_back({i,j});
                    }
                    if(img2[i][j]==1){
                        vp2.push_back({i,j});
                    }
                }
            }
            int ans=0;
            map<pair<int,int>,int>mp;
            for(auto it1:vp1){
                for(auto it2:vp2){
                    int a=it1.first-it2.first;
                    int b=it1.second-it2.second;
                    mp[{a,b}]++;
                    ans=max(ans,mp[{a,b}]);
                }
            }
            return ans;

---

*Originally published on [Coder OP](https://paragraph.com/@coder-op/leetcode-835-image-overlap)*
