Given a source word, a target word, and an English dictionary, transform the source word to the target by changing, adding, or removing one character at a time, such that all intermediate words are valid English words. Return the transformation chain with the smallest number of intermediate words.
The problem can be modeled as a graph where each node is a word, and there is an edge between two words if you can transform one into the other by changing, adding, or removing a single letter. The shortest transformation sequence can be found using Breadth-First Search (BFS).
Build a graph where each word is a node, and edges exist between words that can be transformed into each other by one operation (change, add, remove a letter).
Use BFS to find the shortest path from the source word to the target word.
Return the path if found, otherwise return an empty list.
from collections import deque
classSolution:
defwordLadder(self, source, target, dictionary):
word_set = set(dictionary)
if target notin word_set or source notin word_set:
return []
defneighbors(word):
res = set()
letters ='abcdefghijklmnopqrstuvwxyz'# Change a letterfor i in range(len(word)):
for c in letters:
if c != word[i]:
w = word[:i] + c + word[i+1:]
if w in word_set:
res.add(w)
# Remove a letterfor i in range(len(word)):
w = word[:i] + word[i+1:]
if w in word_set:
res.add(w)
# Add a letterfor i in range(len(word)+1):
for c in letters:
w = word[:i] + c + word[i:]
if w in word_set:
res.add(w)
return res
queue = deque([[source]])
visited = set([source])
while queue:
path = queue.popleft()
last = path[-1]
if last == target:
return path
for nei in neighbors(last):
if nei notin visited:
visited.add(nei)
queue.append(path + [nei])
return []