Word Ladder
Find the length of the shortest transformation sequence from beginWord to endWord using BFS.
01The problem
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s_1 -> s_2 -> ... -> s_k such that:
- Every adjacent pair of words differs by a single letter.
- Every
s_ifor1 <= i <= kis inwordList. Note thatbeginWorddoes not need to be inwordList. s_k == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
| Input | Output | Why |
|---|---|---|
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] | 5 | Shortest ladder: hit -> hot -> dot -> dog -> cog (5 words). |
Constraints
1 <= beginWord.length <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000beginWord != endWord- All strings in
wordListconsist of lowercase English letters. - All strings in
wordListare unique.
Loading the rest of the lesson…