leetcode: Word Ladder I
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
A1s one shortest transformation is
"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
Solution and Precautions:
This problem could be solve by BFS from the start to the end, once the end is found, just return the distance from the end to the start. It is a standard BFS problem. Several issues need to be addressed before successfully solving this problem by BFS:
(1) Instead of building the graph explicitly, one should perform the search on the fly by testing each possible neighbor of a word (by chaning each character in that word, there is 25 * word.size() number of different neightbors), whether this neighbor is in the given dictionary
(2) The start and end word might be be not in the dictionary, always insert the start and end word into the given dictionary before heading into BFS