Skip to content

Commit fe22fea

Browse files
Refactor word_ladder to include path tracking
Updated the word_ladder function to return the transformation path along with the number of steps. Enhanced the main block to display the results more clearly.
1 parent 6dff643 commit fe22fea

File tree

1 file changed

+30
-10
lines changed

1 file changed

+30
-10
lines changed

intermediate/word_ladder.py

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,58 @@
11
from collections import deque, defaultdict
22

33
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+
"""
418
wordSet = set(wordList)
519
if endWord not in wordSet:
6-
return 0
20+
return 0, []
721

8-
# Preprocess: create patterns like h*t, ho*
22+
# Preprocess: create wildcard patterns (e.g., h*t, ho*)
923
neighbors = defaultdict(list)
1024
for word in wordSet:
1125
for i in range(len(word)):
1226
pattern = word[:i] + "*" + word[i+1:]
1327
neighbors[pattern].append(word)
1428

15-
# BFS
16-
queue = deque([(beginWord, 1)])
29+
# BFS with path tracking
30+
queue = deque([(beginWord, [beginWord])])
1731
visited = set([beginWord])
1832

1933
while queue:
20-
word, steps = queue.popleft()
34+
word, path = queue.popleft()
2135
if word == endWord:
22-
return steps
36+
return len(path), path
2337

2438
for i in range(len(word)):
2539
pattern = word[:i] + "*" + word[i+1:]
2640
for nei in neighbors.get(pattern, []):
2741
if nei not in visited:
2842
visited.add(nei)
29-
queue.append((nei, steps + 1))
43+
queue.append((nei, path + [nei]))
3044

31-
return 0
45+
return 0, []
3246

3347

3448
if __name__ == "__main__":
3549
begin = "hit"
3650
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

Comments
 (0)