← Graph Exploration

Micro-Drill #238 — Word Ladder BFS

Graph Exploration Target: 15s

BFS with implicit graph: each word connects to words differing by one letter. Try all 26 replacements at each position.

from collections import deque

def ladderLength(beginWord, endWord, wordList):
    words = set(wordList)
    if endWord not in words: return 0
    q = deque([(beginWord, 1)])
    visited = {beginWord}
    while q:
        word, steps = q.popleft()
        for i in range(len(word)):
            for c in 'abcdefghijklmnopqrstuvwxyz':
                nw = word[:i] + c + word[i+1:]
                if nw == endWord: return steps + 1
                if nw in words and nw not in visited:
                    visited.add(nw)
                    q.append((nw, steps + 1))
    return 0

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #237 Micro #239 →