126. Word Ladder II
Problem description:
Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) 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 an empty list 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:
Input:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
Output:
[
[“hit”,”hot”,”dot”,”dog”,”cog”],
[“hit”,”hot”,”lot”,”log”,”cog”]
]
Example 2:
Input:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
Output: []
Explanation: The endWord “cog” is not in wordList, therefore no possible transformation.
Solution:
- Do BFS layer by layer
- After a layer is done, remove the newLayer keys from wordSet. This is to prevent loop. Note that we don’t remove from set when adding newWord, this is because other traverse in the same layer might still use it
1 | class Solution: |
This is a follow up for 127. Word Ladder. If you have this question on interview, maybe go with a naive BFS solution, then improve it with bi-direction BFS.
The solution came with one direction BFS, the step is as follows.
- Use BFS to solve question, so we need a queue.
queue<vector<string>> paths
, to store the paths in current level. - A dictionary that help to search if a mutate string is in wordlist. The mutate string is created by the same method in 127. Word Ladder. For each character in a word, try to change it to another character, and check whether if it’s in the dictionary.
- Once we know the words in previous level(can think of as the BFS level), we can not use those words again, so we need a set(
unordered_set<string> words
) to record the used string on this level. - Maintain a
minlevel
to speed up the process. Because if we can find a path to findendWord
in 5 hops, then we don’t need to find any path that is greater than 5.
1 | class Solution { |
reference:
https://www.youtube.com/watch?v=lmypbtgdpuQ
http://www.cnblogs.com/grandyang/p/4548184.html
https://goo.gl/4rcWS6
https://goo.gl/t1vxXg