Shortest Transformation Sequence
You are given a begin_word, an end_word, and a dictionary
word_list. Find the length of the shortest transformation
sequence from begin_word to end_word, where:
- Each step changes exactly one letter.
- Every intermediate word produced (including
end_word) must exist inword_list. begin_worddoes not need to be inword_list.
Return the number of words in the shortest such sequence (including
both begin_word and end_word), or 0 if no such sequence exists.
Example 1
Input: begin_word = "hit", end_word = "cog",
word_list = ["hot","dot","dog","lot","log","cog"]
Output: 5 — one shortest sequence is
"hit" -> "hot" -> "dot" -> "dog" -> "cog".
Example 2
Input: begin_word = "hit", end_word = "cog",
word_list = ["hot","dot","dog","lot","log"]
Output: 0 — "cog" is not in word_list, so no sequence can end
there.
Constraints
1 <= begin_word.length <= 10end_word.length == begin_word.length- All words consist of lowercase English letters and have the same length.
1 <= word_list.length <= 5000, all words distinct.
Share this question