Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Image_Overlap.cpp #4

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions 6 CP/LEETCODE/Image_Overlap.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Image Overlap
// Problem link:
// https://leetcode.com/problems/image-overlap/

/*
Intution:
Same overlapping zone would share the same relative positional differnece(linear transformation vector).
**Vab = (Xb - Xa, Yb - Ya)**
```

IMG 1 IMG 2
1 1 0 0 0 0
0 1 0 0 1 1
0 1 0 0 0 1

// Subtracting the co-ordinates

{0,0} - {1,1} = { -1 , -1 }
{0,0} - {1,2} = { -1, -2 }
{0,0} - {2, 2} = { -2, -2 }

{0,1} - {1,1} = { -1 , 0 }
{0,1} - {1,2} = { -1 , -1 }
{0,1} - {2, 2} = { -2, -1 }

{0,2} - {1,1} = { -1 , 1 }
{0,2} - {1,2} = { -1 , 0 }
{0,2} - {2,2} = { -2 , 0 }

and count of { -1 , -1 } is the max overlaping zone = 3 .
*/

// Implementation:

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
vector<pair<int, int>> nonZeroCells(vector<vector<int>>& img){
// filter out those non-zero cells in each matrix respectively.
vector<pair<int, int>> res;
for(int i = 0; i < img.size(); i++){
for(int j = 0; j < img.size(); j++){
if(img[i][j] == 1)
res.push_back({i,j});
}
}
return res;
}
int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {
vector<pair<int, int>> AOnes = nonZeroCells(img1); // {row, col}
vector<pair<int, int>> BOnes = nonZeroCells(img2);
int maxOverlaps = 0;
// calculate the corresponding relative positional differnece(linear transformation vector)
// as Vab = (Xb - Xa, Yb - Ya)
// (row, col) -> count
map<pair<int, int>, int> groupCount;
for(auto a: AOnes){
for(auto b: BOnes){
pair<int, int> val = {b.first-a.first, b.second-a.second};
// same overlapping zone would share the same relative positional differnece(linear transformation vector).
groupCount[val]++;
maxOverlaps = max(maxOverlaps, groupCount[val]);
}
}
return maxOverlaps;
}
};