Word Ladder
Problem statement
Given distinct words beginWord and endWord, and a dictionary wordList, find the shortest sequence of words that changes beginWord into endWord. Return the number of words in that sequence.
Each step changes exactly one letter. Every word after beginWord, including the target, must belong to the dictionary. Return 0 if no such sequence exists. The beginning word need not be in the dictionary.
Function
ladderLength(beginWord: String, endWord: String, wordList: List<String>) → intExamples
Example 1
beginWord = "hit"endWord = "cog"wordList = ["hot","dot","dog","lot","log","cog"]return = 5One shortest sequence is hit → hot → dot → dog → cog, containing five words.
Example 2
beginWord = "hit"endWord = "cog"wordList = ["hot","dot","dog","lot","log"]return = 0The target is absent from the dictionary.
Example 3
beginWord = "a"endWord = "c"wordList = ["a","b","c"]return = 2Change the one letter directly from a to c.
Constraints
1 <= beginWord.length = endWord.length <= 10.0 <= wordList.length <= 5000; dictionary words are distinct and have the same length as the beginning word.- Every word contains lowercase English letters only;
beginWord != endWord.