题目
链接:https://leetcode.com/problems/image-overlap/
Level: Medium
Discription:
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.
Note:
- 1 <= A.length = A[0].length = B.length = B[0].length <= 30
- 0 <= A[i][j], B[i][j] <= 1
代码
class Solution {
public:
int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
map<vector<int>,int> count;
int max=0;
for(int i=0; i<A[0].size()*A[0].size(); i++ )
{
int AX=i/A[0].size();
int AY=i%A[0].size();
if(A[AX][AY]==0)
continue;
for(int j=0;j<B[0].size()*B[0].size(); j++)
{
int BX=j/B[0].size();
int BY=j%B[0].size();
if(B[BX][BY]==1)
{
vector<int> temp;
temp.push_back(BX-AX);
temp.push_back(BY-AY);
if(count.find(temp)!=count.end())
{
count[temp]++;
}
else
count[temp]=1;
max = count[temp]>max ? count[temp] : max;
}
}
}
return max;
}
};
思考
- 算法时间复杂度为O(\(n^4\)),空间复杂度为O(\(n^2\) ),n是矩阵的边长。
- 思路是统计转移方向向量的个数,一个二元数组即可记录所有可能的转移。因为使用map和vector,并且全部遍历了一遍,最终的时间复杂度和空间复杂度都很高。
- 通过测试发现这题的数据有问题。看到一个解法直接去数转移后的重叠1的个数,但是只考虑了向右向下和向左向上的转移,但是也通过了。而这样的数据就通不过了:
[[0,1,1],[0,1,1],[0,0,0]]
[[0,0,0],[1,1,0],[1,1,0]] - 由上面的另一种题解说明,通过模拟转移后的矩阵,计算重叠的1的个数的思路是可行的,运行时间和空间都减少了10多倍。但是仍然没有想到复杂度更低的算法,效率更高的算法可能用到FFT等信号处理的知识,暂时就不研究了。
原文地址:https://www.cnblogs.com/zuotongbin/p/10498673.html
时间: 2024-10-08 16:06:08