I just came through this question , and I could not think any better approach for other than bruteforce Given a 2D array of chars and a raw list of valid words.
1) Find all the valid words from the array. From each element in the array, you can traverse up, down, right or left.
Eg,
g o d b o d y
t a m o p r n
u i r u s m p
valid words from the above 2D array -> god, goat, godbody, amour,….
Make sure you have an alphabetically sorted list of valid words. You could build this in n lg n time.
Now you have this sorted list, you could verify if a sequence of characters is a start of a correct word in lg n time.
Use a set of valid words to validate if a sequence of letters is a valid word (in constant time).
Now call getWords(input, startX, startY, new ArrayList(), “”) for every startposition and merge the resulting lists:
This way you will find your answer in O(x^2 * y^2 * lg w) time, with x and y dimensions of char array and w the size of the valid word list. That is not better than worst case (given the lg w validation), but that does not seem possible to me. The expected runtime is better this way.
If the list of valid words is small, you could also build a set for all valid starts of a correct word. In that case, you could verify in constant time if you are on your way to a correct word, and worst case is reduced to O(x^2 * y^2).
Good luck.