Algorithm for searching grid in different direction
Today a work mate posed a question to me. Given a grid of characters and a list of words one would have to find every occurrence of that word in the grid both horizontally, vertically and diagonally.
The solution we came up with works and does the trick but I am interested to see how other peo开发者_Go百科ples minds tick.
Insert each word in the list in a trie, or hash table or any dictionary.
Now, for each position in your grid, go horizontally, vertically and diagonally and see if you get matches in the dictionary. This should give you O(N^3)
worst case complexity, where N
is the size of the grid. Otherwise it's O(N^2*averageWordLength)
I think.
精彩评论