Word Ladder II

Question (LC.126)

Given a beginWord and an endWord, find all shortest transformation sequences from beginWord to endWord.

Example

I: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
O: [["hit", "hot", "dot", "dog", "cog"], ["hit", "hot", "lot", "log", "cog"]]

I: beginWord = "red", endWord = "tax", wordList = ['ted', 'tex', 'red', 'tax', 'tad', 'den', 'rex', 'bee']
O: [['red', 'ted', 'tad', 'tax'], ['red', 'ted', 'tex', 'tax'], ['red', 'rex', 'tex', 'tax']]

I: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
O: []
simple example with multiple shortest paths

Analysis

finding all shortest paths in a simple graph

A simple BFS is not enough to find all shortest paths because you simply do not know which one is the shortest one yet.

This question is essentially finding all shortest paths in a simple graph.

The first step is to build a visited map where each node stores the shortest distance to arrive and a list of nodes that can get there with that distance.

The second step is to find all possible combinations from the visited map.

Code

Complexity

Time O(V+E) for bfs then O(V + E) worst case for the dfs

Space O(V+E) for visited dict and O(nCr) for the paths

Reference

Last updated