问题
So following is an interview problem.
Given two N2 matrices with entries being
0
or1
. How can we find out the number of maximum overlapping1
's possible?
Note: You can only move the matrix upward, downward, leftward and rightward, so rotation is not allowed
Currently I'm stuck at the most naive O(N^4)
method, which being align the top left corner of one matrix to every possible position of the other matrix and count the all the overlap 1s.
Example:
[0 1 0] [0 0 1]
A: [1 0 0] B: [0 0 1]
[1 0 0] [0 0 0]
Then the number of maximum overlapping 1s are 2, that we alight (0,2) of B to (1,0) of A, then (0,2) and (1,0) are both 1, and (1,2) and (2,0) are both 1.
Can it be optimise from O(N4)?
回答1:
If floating-point arithmetics calculations are possible, this problem might be solved with 2D cross-correlation (using fast Fourier transform intrinsically) in O(n^2 logn)
time. This method is used in 2D pattern searching.
Not so obvious tip: to implement correlation and get proper results, one should shift values to make "signals" bi-polar (transform zeros to -1 or subtract matrix average from all matrix elements)
Calculate correlation matrix, find index (dx,dy)
of maximum value - it should correspond to align vector.
来源:https://stackoverflow.com/questions/50263570/align-2-matrice-for-maximum-overlap