
Word Ladder II
Write a Java program to find all shortest transformation sequences from a beginWord to an endWord, where each sequence consists of valid words and each transformation changes exactly one letter. Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., endWord] where s1, s2, etc. are valid words from the wordList. A transformation sequence is valid if:
1. Only one letter can be changed at a time
2. Each transformed word must exist in the wordList
3. beginWord does not need to be in wordList
4. endWord must be in wordList
Return an empty list if there is no such transformation sequence.
Example 1
- Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
- Output: [["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"]]
- Explanation:
Start from "hit" and transform to "hot" by changing 'i' to 'o'.
From "hot", we can transform to either "dot" (changing 'h' to 'd') or "lot" (changing 'h' to 'l').
From "dot", transform to "dog" by changing 't' to 'g'.
From "lot", transform to "log" by changing 't' to 'g'.
From "dog" or "log", transform to "cog" by changing 'd' to 'c' or 'l' to 'c'.
There are two valid transformation sequences of length 5: ["hit","hot","dot","dog","cog"] and ["hit","hot","lot","log","cog"].
Example 2
- Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
- Output: []
- Explanation:
We start from "hit" and can transform to "hot".
From "hot", we can transform to "dot" or "lot".
From "dot", we can transform to "dog".
From "lot", we can transform to "log".
However, "cog" is not in the wordList, so there is no valid transformation sequence to reach "cog".
Constraints
- 1 <= beginWord.length <= 5
- endWord.length == beginWord.length
- 1 <= wordList.length <= 500
- wordList[i].length == beginWord.length
- beginWord, endWord, and wordList[i] consist of lowercase English letters
- beginWord != endWord
- All the words in wordList are unique
- Time Complexity: O(N * M * M), where N is the number of words and M is the length of each word
- Space Complexity: O(N * M)
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use a breadth-first search (BFS) to find the shortest path length from beginWord to endWord
- During BFS, build a graph that represents all possible transformations
- Use a set to keep track of visited words at each level to avoid cycles
- After finding the shortest path length, use depth-first search (DFS) to find all possible paths with that length
- To efficiently find all words that differ by one character, consider each position in the word and try all 26 possible characters