|
1 | 1 | from collections import deque, defaultdict |
2 | 2 |
|
3 | 3 | def word_ladder(beginWord, endWord, wordList): |
| 4 | + """ |
| 5 | + Finds the shortest transformation sequence from beginWord to endWord such that: |
| 6 | + - Only one letter can be changed at a time. |
| 7 | + - Each transformed word must exist in the wordList. |
| 8 | +
|
| 9 | + Returns: |
| 10 | + A tuple (steps, path) where: |
| 11 | + - steps is the number of words in the shortest transformation sequence. |
| 12 | + - path is a list of words representing the transformation. |
| 13 | +
|
| 14 | + Example: |
| 15 | + >>> word_ladder("hit", "cog", ["hot","dot","dog","lot","log","cog"]) |
| 16 | + (5, ['hit', 'hot', 'dot', 'dog', 'cog']) |
| 17 | + """ |
4 | 18 | wordSet = set(wordList) |
5 | 19 | if endWord not in wordSet: |
6 | | - return 0 |
| 20 | + return 0, [] |
7 | 21 |
|
8 | | - # Preprocess: create patterns like h*t, ho* |
| 22 | + # Preprocess: create wildcard patterns (e.g., h*t, ho*) |
9 | 23 | neighbors = defaultdict(list) |
10 | 24 | for word in wordSet: |
11 | 25 | for i in range(len(word)): |
12 | 26 | pattern = word[:i] + "*" + word[i+1:] |
13 | 27 | neighbors[pattern].append(word) |
14 | 28 |
|
15 | | - # BFS |
16 | | - queue = deque([(beginWord, 1)]) |
| 29 | + # BFS with path tracking |
| 30 | + queue = deque([(beginWord, [beginWord])]) |
17 | 31 | visited = set([beginWord]) |
18 | 32 |
|
19 | 33 | while queue: |
20 | | - word, steps = queue.popleft() |
| 34 | + word, path = queue.popleft() |
21 | 35 | if word == endWord: |
22 | | - return steps |
| 36 | + return len(path), path |
23 | 37 |
|
24 | 38 | for i in range(len(word)): |
25 | 39 | pattern = word[:i] + "*" + word[i+1:] |
26 | 40 | for nei in neighbors.get(pattern, []): |
27 | 41 | if nei not in visited: |
28 | 42 | visited.add(nei) |
29 | | - queue.append((nei, steps + 1)) |
| 43 | + queue.append((nei, path + [nei])) |
30 | 44 |
|
31 | | - return 0 |
| 45 | + return 0, [] |
32 | 46 |
|
33 | 47 |
|
34 | 48 | if __name__ == "__main__": |
35 | 49 | begin = "hit" |
36 | 50 | end = "cog" |
37 | | - words = ["hot","dot","dog","lot","log","cog"] |
38 | | - print(word_ladder(begin, end, words)) # Output: 5 |
| 51 | + words = ["hot", "dot", "dog", "lot", "log", "cog"] |
| 52 | + |
| 53 | + steps, path = word_ladder(begin, end, words) |
| 54 | + if steps: |
| 55 | + print(f"Shortest transformation length: {steps}") |
| 56 | + print("Transformation path:", " → ".join(path)) |
| 57 | + else: |
| 58 | + print("No transformation sequence found.") |
0 commit comments