题目描述
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.
思路:
与上一题不同,这次需要存储所有的最短路径,就不能在入队前把字典中的节点除去。我们需要一个队列存储路径,每次取出队列头的路径,把队头路径的最后一个节点拿出来寻找下一个可达的节点并存入set中,如果可达节点为end节点,则将路径保存进结果列表中,如果不为end节点,则生成新的路径存入队尾。如果路径长度大于当前路径长度(也就是层数),则更新当前路径长度,同时将set中节点都从字典中清除,因为这些节点都是上层的节点,我们不希望再走回头路,这肯定不是最短路径了。如果发现当前路径长度已经大于到达end节点的路径长度了,则后面的路径都不是最短路径了,直接break。
代码:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict) {
ArrayList<ArrayList<String>> res = new ArrayList();
Queue<ArrayList<String>> paths = new LinkedList();
ArrayList<String> startPath = new ArrayList();
startPath.add(start);
paths.offer(startPath);
HashSet<String> nodeToMove = new HashSet();
int level = 1, lastLevel = Integer.MAX_VALUE;
while (!paths.isEmpty()){
ArrayList<String> path = paths.poll();
// 如果当前头部的路径长度已经超过level,说明已经到了下一层,之前的节点都可以清除了
if (path.size() > level){
// 从字典中清除节点
dict.removeAll(nodeToMove);
// 清除记录的节点
nodeToMove.clear();
// 更新路径长度
level = path.size();
// 如果长度大于到达终点的最短路径,则退出循环
if (level > lastLevel) break;
}
// 拿到头部路径的最后一个节点
String last = path.get(path.size() - 1);
char str[] = last.toCharArray();
// 寻找下一个节点
for (int i=0; i<str.length; i++){
char original = str[i];
for (char c='a'; c<='z'; c++){
str[i] = c;
String next = new String(str);
// 如果节点在字典中存在
if (dict.contains(next)){
// 记录要清除的节点
nodeToMove.add(next);
// 创建新的路径并把下一个节点加入
ArrayList<String> nextPath = new ArrayList(path);
nextPath.add(next);
// 如果已经到达终点则加入结果的列表中,并记录最短路径长度
if (next.equals(end)){
res.add(nextPath);
lastLevel = level;
}
// 否则将路径加入队列的队尾
else {
paths.offer(nextPath);
}
}
str[i] = original;
}
}
}
return res;
}
}
网友评论