Find number of occurrence of a word in a 2D matrix of Characters

algorithms

Given a two dimensional matrix of alphabets, search the given word in all directions. Below is an example to search for the word "TEAM":

No of occurrences is 4 in matrix below.

enter image description here

What is the best approach to solve this?
Its not a dictionary word. Its simply sequence searching in all the directions.

Best Answer

I did something similar time ago. You should take advantage of the fact that words are a ordered set of characters. So, you perform a linear search over the matrix for the first letter, then you recursively call the directional search.

To simplify computational complexity you can add some constraint, eg, if word.length > number of characters on that direction don't start searching.

The recursive function signature would be like:

boolean search(string word, int direction)

with terminal case

if (word.length==1) return isNextLetterInDirection(word, direction);

and the search being

search(substring(word, 0, word.length-1), direction);

This algorithm also cover palindrome cases and words including their syllables.

Related Topic