align 2 matrice for maximum overlap

心不动则不痛 提交于 2020-01-14 10:23:19

问题


So following is an interview problem.

Given two N2 matrices with entries being 0 or 1. How can we find out the number of maximum overlapping 1'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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!