diff --git a/6 CP/LEETCODE/Image_Overlap.cpp b/6 CP/LEETCODE/Image_Overlap.cpp new file mode 100644 index 0000000..1608176 --- /dev/null +++ b/6 CP/LEETCODE/Image_Overlap.cpp @@ -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 +using namespace std; + +class Solution { +public: + vector> nonZeroCells(vector>& img){ + // filter out those non-zero cells in each matrix respectively. + vector> 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>& img1, vector>& img2) { + vector> AOnes = nonZeroCells(img1); // {row, col} + vector> 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, int> groupCount; + for(auto a: AOnes){ + for(auto b: BOnes){ + pair 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; + } +};