Problem 527712 · hard · Level 05 Advanced Algorithms & Graphs

Word Ladder

bfs · shortest path · implicit graph · strings

The hardest part of many BFS problems is seeing the graph at all. Here the nodes are words and two words are adjacent when they differ in exactly one letter; nobody hands you that graph, you generate neighbours as you go.

In Lewis Carroll's word-ladder puzzle you climb from one word to another by changing one letter at a time, and every rung must be a real word. Write ladder_length(begin_word, end_word, word_list) that returns the number of words on the shortest ladder from begin_word to end_word, counting both ends. Every rung after begin_word must come from word_list, although begin_word itself need not be there. Return 0 when no ladder exists.

Examples

Input:  begin_word = "big", end_word = "cat",
        word_list = ["bag", "rag", "rat", "cat", "bog", "cog", "cot"]
Output: 5
Explanation: big -> bag -> rag -> rat -> cat (5 words); big -> bog -> cog -> cot -> cat is just as short

Input:  begin_word = "big", end_word = "cat",
        word_list = ["bag", "rag", "rat", "bog", "cog", "cot"]
Output: 0
Explanation: "cat" is not in the list

Constraints

  • 1 <= len(begin_word) <= 10, all words have the same length, lowercase letters
  • begin_word != end_word
  • 1 <= len(word_list) <= 5000
  • Target: O(N * L * 26) time where N is the number of words and L their length

Goals

  • Run BFS on a graph whose edges are generated on the fly instead of stored
  • Count BFS levels to get a shortest path length in an unweighted graph
  • Generate neighbours efficiently by mutating one letter at a time
Starting Python…