5

I tried to solve the problem of two dimensional search using a combination of Aho-Corasick and a single dimensional KMP, however, I still need something faster.

To elaborate, I have a matrix A of characters of size n1*n2 and I wish to find all occurrences of a smaller matrix B of size m1*m2 and I want that to be in O(n1*n2+m1*m2) if possible.

For example:

A = a b c b c b
    b c a c a c
    d a b a b a
    q a s d q a

and

B = b c b
    c a c
    a b a

the algorithm should return the indexes of say, the upper left corner of the match, which in this case should return (0,1) and (0,3). notice that the occurrences may overlap.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Ouais Alsharif
  • 317
  • 1
  • 4
  • 16
  • Expand Your question. What exactly is the problem? You have a 2D array of characters, an wish to find vertical or horizontal words? – maniek Feb 15 '12 at 23:33
  • @maniek- I think the OP wants to search for a 2D grid of characters inside of another 2D grid of characters. – templatetypedef Feb 16 '12 at 05:16

1 Answers1

4

There is an algorithm called the Baker-Bird algorithm that I just recently encountered that appears to be a partial generalization of KMP to two dimensions. It uses two algorithms as subroutines - the Aho-Corasick algorithm (which itself is a generalization of KMP), and the KMP algorithm - to efficiently search a two-dimensional grid for a pattern.

I'm not sure if this is what you're looking for, but hopefully it helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • What do you mean by "too slow?" Are you sure that the algorithm is the culprit rather than the implementation? Also, how big are the grids that you're working with? – templatetypedef Feb 16 '12 at 19:53
  • too slow: I'm using black box testing, that is, the data its tested on is not available to me. It's an online problem, I submit my answers and my solution got a .37 seconds using rabin karp, I tried doing it using the fore mentioned approach and it took .82. There's someone who managed to do it in .08 (you can see a list of names of the people that solved the problem and their times) and I was trying to get there. – Ouais Alsharif Feb 16 '12 at 21:28
  • Could You post the online judge link? – maniek Feb 17 '12 at 21:05
  • @maniek sorry, didn't notice your response earlier. here's the link: http://www.spoj.pl/problems/ARDA1/ I wanted to get something close in time to the best solver, that is .08 seconds, but i dropped it since then – Ouais Alsharif Feb 28 '12 at 12:02
  • I think You can have O(n1*n2 + m1*m2) Rabin Karp – maniek Feb 28 '12 at 15:19