Advanced Graphs Weighted shortest paths
476. Word Ladder II
You are given two words, beginWord and endWord, and a list of words, wordList. All of them have the
same length.
A ladder is a sequence of words that starts with beginWord and ends with endWord. Each word in it
differs from the word before it in exactly one position. Every word after beginWord must be in
wordList; beginWord itself does not have to be.
Return every shortest ladder, each as its list of words from beginWord to endWord. The ladders may
come in any order. If no ladder exists, return an empty list.
Example 1
Input: beginWord = "cat"
endWord = "dog"
wordList = ["hot",
"cot",
"dog",
"cog",
"dot",
"hog",
"cut"]
[["cat","cot","cog","dog"],
["cat","cot","dot","dog"]]Explanation: Both ladders have four words, and no ladder is shorter. cat → cot → hot → hog → dog is also a ladder, but it has five words, so it is not returned.
Example 2
Input: beginWord = "tree"
endWord = "leaf"
wordList = ["free", "flee", "flea", "leaf"]
[]Explanation: tree → free → flee → flea works, but leaf differs from every other word in more than one position. So no
ladder reaches it, even though it is in wordList.
Example 3
Input: beginWord = "a"
endWord = "c"
wordList = ["a", "b", "c"]
[["a","c"]]Explanation: a and c differ in their only letter, so the ladder a → c has two words. a → b → c has three. beginWord
is in the list here, and it still appears only once, at the start.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ beginWord.length ≤ 10endWord.length == beginWord.length1 ≤ wordList.length ≤ 5000wordList[i].length == beginWord.lengthbeginWord,endWordand everywordList[i]hold only lowercase English letters.beginWord != endWord- The words in
wordListare distinct. - The shortest ladders hold at most 105 words in all.
Clarifying questions
What you would ask an interviewer before writing any code.