Word Ladder

Hard Graphs AI round

beginWord and endWord are words of lower case letters, both of the same length, and wordList is a list of words of that length too.

A ladder goes from beginWord to endWord one word at a time. Each step changes exactly one letter of the word, and the word it makes must be in wordList. beginWord itself need not be in wordList, but every word after it must be, endWord included.

Return the number of words in the shortest ladder, beginWord and endWord included, or 0 if there is no ladder.

Example 1

Input: beginWord = "cold", endWord = "warm", wordList = ["cord","card","corm","ward","word","worm","warm"]
Output: 5

cold, cord, card, ward, warm: each word changes one letter of the one before, and all but cold are in the list. That is five words, and none shorter can work, as cold and warm differ in all four letters. cold, cord, corm, worm, warm is another of five.

Example 2

Input: beginWord = "lead", endWord = "gold", wordList = ["load","goad","lord"]
Output: 0

Example 3

Input: beginWord = "pin", endWord = "pan", wordList = ["pit","pin","pan"]
Output: 2

Constraints

  • 1 ≤ beginWord.length ≤ 10
  • endWord and every word of wordList have as many letters as beginWord
  • 1 ≤ wordList.length ≤ 500
  • Every word uses only the lower case letters a to z
  • beginWord ≠ endWord, and the words of wordList are all different

Watch the explanation

More Graphs

All Graphs problems