This is a twofold question, because I'm out of ideas on how to implement this most efficiently.
I have a dictionary of 150,000 words, stored into a Trie implementation, here's what my particular implementation looks like:
A user is given a provided with two words. With the goal being to find the shortest path of other english words (changed by one character apiece) from the start word to the end word.
For example:
Start: Dog
End: Cat
Path: Dog, Dot, Cot, Cat
Path: Dog, Cog, Log, Bog, Bot, Cot, Cat
Path: Dog, Doe, Joe, Joy, Jot, Cot, Cat
My current implementation has gone through several iterations, but the simplest I can provide pseudocode for (as the actual code is several files):
var start = "dog";
var end = "cat";
var alphabet = [a, b, c, d, e .... y, z];
var possible_words = [];
for (var letter_of_word = 0; letter_of_word < start.length; letter_of_word++) {
for (var letter_of_alphabet = 0; letter_of_alphabet < alphabet.length; letter_of_alphabet++) {
var new_word = start;
new_word.characterAt(letter_of_word) = alphabet[letter_of_alphabet];
if (in_dictionary(new_word)) {
add_to.possible_words;
}
}
}
function bfs() {
var q = [];
... usual bfs implementation here ..
}
Knowns:
- A start word and a finish word
- Words are of the same length
- Words are english words
- It is possible for there to not be a path
Question:
My issue is I do not have an efficient way of determining a potential word to try without brute-forcing the alphabet and checking each new word against the dictionary. I know there is a possibility of a more efficient way using prefixes, but I can't figure out a proper implementation, or one that doesn't just double the processing.
Secondly, should I be using a different search algorithm, I've looked at A* and Best First Search as possibilities, but those require weights, which I don't have.
Thoughts?
(26! * length of word)
possible leaves correct?