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 adoneSet
to record which word is already processed to the queue, in other word, ifdoneSet
contains 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
bfs
function, we create adeepsMap
, key is each word, value is the distance to the beginWord, sodeepsMap.put(beginWord, 0);
because distance ofbeginWord
to itself is zero. We do this because some words can also reach theendWord
but they cannot reach thebeginWord
so we want to ignore those words and they will not have depth or in other word, they won’t be insidedeepsMap
. Alsobfs
function will return the minLength integer to theendWord
. -
Then, we use DFS, start from
endWord
to target isbeginWord
to trace this route. If thecurList
size is greater than minLength, we ignore that list. IfcurList
size is equal to minLength, then we check if it’s equal to thebeginWord
. If it is, then add to the result list. If thecurList
size 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 thedeepsMap
but its depth + current depth is greater than minLength, also ignore it; we also need adoneSet
to record the word we already traced in this route.
Solution
1 |
|