Word Ladder

HardGraph BFS and DFS

You are given a start word beginWord, a target word endWord and a dictionary wordList.

A transformation sequence starts at beginWord and ends at endWord, and each word in it differs from the word before it in exactly one letter position (no letters are added, removed or moved). Every word after beginWord must come from wordList; beginWord itself doesn't need to be in the list.

Return the number of words in the shortest transformation sequence, counting both ends, or 0 if no sequence exists.

Constraints

  • 1 <= beginWord.length <= 10, and endWord and every word in wordList have the same length
  • 1 <= wordList.length <= 5000
  • All words consist of lowercase English letters, and beginWord !== endWord
  • wordList may contain duplicates

Examples

Example 1

Input: beginWord = "cold", endWord = "warm", wordList = ["cord","card","ward","warm","worm","word","wore","core","care","ware"]
Output: 5

One shortest sequence is cold → cord → card → ward → warm: 5 words. Other routes (through word and worm) are no shorter.

Example 2

Input: beginWord = "tick", endWord = "tock", wordList = ["tack","tuck","tick"]
Output: 0

"tock" is not in the word list, so no sequence can end with it: 0.

Example 3

Input: beginWord = "ab", endWord = "ac", wordList = ["ac","bc"]
Output: 2

"ab" → "ac" changes one letter, so the sequence has 2 words.

JavaScript you'll use: Map and Set Strings and characters Stacks, queues and deques

/**
 * @param {string} beginWord
 * @param {string} endWord
 * @param {string[]} wordList
 * @return {number}
 */
function ladderLength(beginWord, endWord, wordList) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.