Problem
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:
1 | |
Example 2:
1 | |
1 | |
Explanation
-
First, we build a
map, key is each word, value is a list of words that that’s gotten by changing one character of the key word. For example,{"hot": ["dot","hit"]},{"hit", ["hot"]}. To avoid duplicate, for example, “hot”’s list contains “hit”, and “hit”’s list contains “hot”, so we need to create adoneSetto record which word is already processed to the queue, in other word, ifdoneSetcontains the word, then we wont’ put that word to the queue because we will use BFS. -
Similar to 127. Word Ladder, in order to build map, we need to check each character and for each character, we replace it with “a” to “z” and put the new replace word that are in the list to to the map’s key’s corresponding list.
-
Inside the
bfsfunction, we create adeepsMap, key is each word, value is the distance to the beginWord, sodeepsMap.put(beginWord, 0);because distance ofbeginWordto itself is zero. We do this because some words can also reach theendWordbut they cannot reach thebeginWordso we want to ignore those words and they will not have depth or in other word, they won’t be insidedeepsMap. Alsobfsfunction will return the minLength integer to theendWord. -
Then, we use DFS, start from
endWordto target isbeginWordto trace this route. If thecurListsize is greater than minLength, we ignore that list. IfcurListsize is equal to minLength, then we check if it’s equal to thebeginWord. If it is, then add to the result list. If thecurListsize is less than the minLength, then we want to find and add the word to our sublist. Here, we will use thedeepsMap. If the neightbor word is not in thedeepsMap, then ignore it; if it is in thedeepsMapbut its depth + current depth is greater than minLength, also ignore it; we also need adoneSetto record the word we already traced in this route.
Solution
1 | |