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

前端 未结 4 1475
囚心锁ツ
囚心锁ツ 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:38

    There is no way to do this fast if you only ever need to match one small matrix against one big matrix. But if you need to do many small matrices against big matrices, then preprocess the big matrix.

    A simple example, exact match, many 3x3 matrices against one giant matrix.

    Make a new "match matrix", same size as "big matrix", For each location in big matrix compute a 3x3 hash for each x,y to x+3,y+3 in big matrix. Now you just scan the match matrix for matching hashes.

    You can achieve partial matches with specialized hash functions that give the same hash to things that have the same partial matching properties. Tricky.

    If you want to speed up further and have memory for it, create a hash table for the match matrix, and lookup the hashes in the hash table.

    The 3x3 solution will work for any test matrix 3x3 or larger. You don't need to have a perfect hash method - you need just something that will reject the majority of bad matches, and then do a full match for potential matches in the hash table.

提交回复
热议问题