Fastest way to Find a m x n submatrix in M X N matrix

前端 未结 4 1477
囚心锁ツ
囚心锁ツ 2020-12-10 02:02

I was thinking of a fast method to look for a submatrix m in a bigger mtrix M. I also need to identify partial matches.

Couple of approaches I could think of are :

4条回答
  •  眼角桃花
    2020-12-10 02:34

    I think you cannot just guess where the submatrix is with some approach, but you can optimize your searching.

    For example, given a matrix A MxN and a submatrix B mxn, you can do like:

    SearchSubMatrix (Matrix A, Matrix B)
    
    answer = (-1, -1)
    
    Loop1:
    for i = 0 ... (M-m-1)
    |
    |   for j = 0 ... (N-n-1)
    |   | 
    |   |   bool found = true
    |   |
    |   |   if A[i][j] = B[0][0] then
    |   |   |
    |   |   |   Loop2:
    |   |   |   for r = 0 ... (m-1)
    |   |   |   |   for s = 0 ... (n-1)
    |   |   |   |   |   if B[r][s] != A[r+i][s+j] then
    |   |   |   |   |   |   found = false
    |   |   |   |   |   |   break Loop2
    |   |
    |   |   if found then
    |   |   |   answer = (i, j)
    |   |   |   break Loop1
    |
    return answer
    

    Doing this, you will reduce your search in the reason of the size of the submatrix.

    Matrix         Submatrix         Worst Case:
    1 2 3 4           2 4            [1][2][3] 4
    4 3 2 1           3 2            [4][3][2] 1
    1 3 2 4                          [1][3]{2  4}
    4 1 3 2                           4  1 {3  2}
    
                                     (M-m+1)(N-n+1) = (4-2+1)(4-2+1) = 9
    

    Although this is O(M*N), it will never look M*N times, unless your submatrix has only 1 dimension.

提交回复
热议问题