leetcode: Given two words (start and end), and a dictionary, 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 dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["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.
解题思路:
1、使用图的广度优先搜索策略(BFS);
2、由于要返回所有的最短转换序列,使用unordered_map<string , vector<string>>来存储每个节点的前驱节点;
3、使用递归的形式,将unordered_map<string , vector<string>>中存放的节点顺序信息恢复成转换序列。
代码:
疑点:根据unordered_map<string , vector<string>>中的节点信息,从end节点开始,递归往前推导,得出来的转换序列是全部转换序列,还是所有最短转换序列?答案肯定是返回所有的最短转换序列,首先可以这样想,在广度优先搜索的时候,Layer[pre]和Layer[cur]像剥洋葱一样,一层一层的向前推进,直到搜索到单词end的时候结束,那么从end再一层一层返回,得到的也会是最短的转换序列。换一种思路,假设在原单词表中,单词a可以直接到单词x,即a -> x,也可以经过单词b到单词x,即a -> b -> c ->x。当{a}为当前所搜索的层次时,记录x的前驱是a,b的前驱是a,所以,接下来搜索的一层是{b , x},然后在单词表中删除b、x,由此可以得出,b -> c -> x这个路径是记录不下来的。所以,广度优先搜索记录下来的路径是最短路径。