描述
Given two words (start and end), and a dictionary’s word list, find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,Given:
start = “hit”
end = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
Return
[
[“hit”,”hot”,”dot”,”dog”,”cog”],
[“hit”,”hot”,”lot”,”log”,”cog”]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
分析
这道题比较难,要把所有的最短路径都找出来。其实本质上就是标准的求的图两点间最小路径。先BFS遍历记录路径信息,再DFS反向构建路径。
难点在于第一要维护路径的信息,第二不能像上一题那样直接从字典中删掉入列的词(因为它可能存在于两条最短路径上)。写了很久没有写对,先放一个别人的正确答案,解法很漂亮,回头详细分析。
代码
Python
1 | from collections import defaultdict |