Problem
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
If we solve this problem manually, for example from example1, we will find whether “cit” is in the list, no; we try “hot”, yes, it is in the list; then we try “cot” or “hog”, they both not in the list. This method is not working.
-
We can try brute force. For every character in the word, we try to replace each character with ‘a’ to ‘z’. For example, “hit”, we replace the first character with “a”, so it is “ait”; replace it with “b”, so it is “bit”; and we get “cit”, “dit”, “eit”, …, “zit”. We check if these words if it’s the endWord, if not, check if they are in the list, if the word is in the list, then it can potentially be the path to get the endWord.
-
Now, if the word we try is “hot”, and we check it’s in the list, then should we try “hpt”, “hqt”, “hrt”… (BFS) or “aot”, “bot”, “cot”… (DFS)? We know that it’s better to use BFS to find the minimum path, so it’s better to use BFS.
-
In order to improve the performance of searching if the word is in the list, we can put the list of words to a hash set. To use BFS, we need to have a queue. First, put the beginWord to the queue, and pop it out as popWord and try to replace its each character with “a” to “z”. We initialize the res to 2 since that’s the minimum because one is beginWord and antoher one is endWord. Then if the popWord is the same as endWord, we can just return res. If it’s not equal endWord but it’s in the list, then we push it to the queue and increase the level by 1. If this time, the new popWord is the same as the endWord, we can just return result+level.
-
We use the queue size to keep track when we should update level by 1. After we pop queueSize elements, then we can increase level by 1.
Solution
1 |
|