Pattern visualizer
Word Ladder
Treat every word as a vertex and every one-letter change as an edge, and the problem becomes the shortest path in an unweighted graph — which is breadth-first search. Nobody builds that graph up front: from each word, swap every position for every letter a to z and keep the candidates that are still in the word set. Erasing a word from the set the moment it is discovered is what keeps the search linear, because the first route to reach a word is already the shortest, so no later route needs it. The badge on each node is the ladder length that reached it. Animated on: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] — length of the shortest transformation sequence, or 0..
BFS over words: one letter per step, shortest sequence wins
Every one-letter change is an edge
"hit" must become "cog" one letter at a time, and every intermediate word has to be in the list. Each line here joins two words that differ in exactly one letter — so the question is the shortest path in an unweighted graph, and that is exactly what breadth-first search finds.
1FUNCTION ladderLength(beginWord, endWord, wordList):2 dict <- SET OF wordList3 IF endWord NOT IN dict RETURN 04 queue <- [(beginWord, 1)]5 WHILE queue NOT EMPTY6 (word, steps) <- REMOVE FIRST FROM queue7 IF word = endWord RETURN steps8 FOR i FROM 0 TO LENGTH(word) - 19 FOR EACH c IN 'a' TO 'z'10 next <- word WITH word[i] REPLACED BY c11 IF next IN dict12 REMOVE next FROM dict13 APPEND (next, steps + 1) TO queue14 RETURN 0
← / → step · space play · Home restart