04. Word Ladder II
Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord.
How It Works & Algorithmic Design
Solves using Bidirectional BFS Level Graph Construction + Backtracking DFS:
- BFS Level Mapping: Perform BFS starting from
beginWord. Build distance mapdistMap[word]storing shortest steps frombeginWordto every reachable dictionary word. - DFS Path Backtracking: Backtrack from
endWorddown tobeginWord:- Only step to neighbor words where
distMap[neighbor] === distMap[current] - 1.
- Only step to neighbor words where
- Return: All collected minimum length paths.
Why This Approach Works Best
Decoupling minimum distance calculation (BFS) from path generation (DFS) prevents combinatorial path explosion.
Example Walkthrough
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Target conversion.
["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"]
Length 5 paths.
List of both 5-step shortest paths.
All minimum transformations.
Answer: Word Ladder II BFS + DFS implementation
function findLadders(beginWord, endWord, wordList) {
const wordSet = new Set(wordList);
if (!wordSet.has(endWord)) return [];
wordSet.add(beginWord);
const dist = new Map();
const queue = [beginWord];
dist.set(beginWord, 0);
while (queue.length) {
const curr = queue.shift();
const d = dist.get(curr);
for (let i = 0; i < curr.length; i++) {
for (let c = 97; c <= 122; c++) {
const next = curr.substring(0, i) + String.fromCharCode(c) + curr.substring(i + 1);
if (wordSet.has(next) && !dist.has(next)) {
dist.set(next, d + 1);
queue.push(next);
}
}
}
}
if (!dist.has(endWord)) return [];
const res = [];
function dfs(word, path) {
if (word === beginWord) {
res.push([beginWord, ...path]);
return;
}
const d = dist.get(word);
for (let i = 0; i < word.length; i++) {
for (let c = 97; c <= 122; c++) {
const prev = word.substring(0, i) + String.fromCharCode(c) + word.substring(i + 1);
if (dist.get(prev) === d - 1) {
dfs(prev, [word, ...path]);
}
}
}
}
dfs(endWord, []);
return res;
}Build shortest distance level graph using BFS, then generate valid minimum paths using DFS backtracking.
BFS measures shortest levels; DFS reconstructs exact matching paths.
Backtracking backwards from
endWordreduces redundant branching.Time complexity $O(N \cdot L^2)$.