Word ladder
Challenge · Write code · about 20 min
A ladder goes from beginWord to endWord by changing one letter at a time. Each word after beginWord must be in wordList.
Return the number of words in the shortest ladder, counting beginWord and endWord. Return 0 if no ladder exists.
Example 1
Input:
["hit","cog",["hot","dot","dog","lot","log","cog"]]
Output:
5
hit, hot, dot, dog, cog is a ladder of 5 words.
Example 2
Input:
["hit","cog",["hot","dot","dog","lot","log"]]
Output:
0
cog is not in the word list.
Constraints
- 1 ≤ beginWord.length ≤ 10 and all words have the same length
- beginWord ≠ endWord
- 0 ≤ wordList.length ≤ 5000
- Words use lowercase letters a-z only
Learn the idea first: Shortest paths in unweighted graphs; path reconstruction, a visual lesson.
More Shortest paths in unweighted graphs; path reconstruction problems
- Which search finds the fewest stops? Warm-up
- Distance labels Warm-up
- Shortest path length Standard
- Reconstruct the path Standard
- Nearest exit in a maze Standard
- Spot the bug: wrong distances Standard