1 题目理解
题目要求和127是一样的。返回值不一样。返回值要求把最短路径的,具体路径输出。
Input:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
Output:
[
[“hit”,“hot”,“dot”,“dog”,“cog”],
[“hit”,“hot”,“lot”,“log”,“cog”]
]
2 BFS
因为要返回具体的路径。需要修改的地方有2个。
一是不能再有虚拟节点,需要两两比对单词不相同的位数有几个,判断是否可以添加边。
二是,队列中的值不再是节点本身,还需要把到达这个节点的具体路径记录下来。
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
List<List<String>> answer = new ArrayList<List<String>>();
if(wordList==null || !wordList.contains(endWord)){
return answer;
}
if(!wordList.contains(beginWord)){
wordList.add(beginWord);
}
Map<String,List<String>> allComboDict = addWord(wordList);
Queue<Pair> queue = new LinkedList<Pair>();
List<String> beginList = new ArrayList<String>();
beginList.add(beginWord);
queue.offer(new Pair(beginWord,beginList));
Map<String,Integer> visited = new HashMap<String,Integer>();
visited.put(beginWord,1);
while(!queue.isEmpty()){
Pair pair = queue.poll();
String node = pair.word;
List<String> list = pair.list;
if(node.equals(endWord)){
answer.add(list);
}else{
if(allComboDict.get(node)!=null){
for(String toNode: allComboDict.get(node)){
if(!visited.containsKey(toNode) || visited.get(toNode)>=list.size()+1){
List<String> tmp = new ArrayList<String>(list);
tmp.add(toNode);
queue.offer(new Pair(toNode,tmp));
visited.put(toNode,tmp.size());
}
}
}
}
}
return answer;
}
private Map<String,List<String>> addWord(List<String> wordList){
Map<String,List<String>> allComboDict = new HashMap<String,List<String>>();
for(int i=0;i<wordList.size();i++){
for(int j=i+1;j<wordList.size();j++){
if(transform(wordList.get(i),wordList.get(j))){
List<String> list = allComboDict.getOrDefault(wordList.get(j),new ArrayList<String>());
list.add(wordList.get(i));
allComboDict.put(wordList.get(j),list);
List<String> list2 = allComboDict.getOrDefault(wordList.get(i),new ArrayList<String>());
list2.add(wordList.get(j));
allComboDict.put(wordList.get(i),list2);
}
}
}
System.out.println(allComboDict);
return allComboDict;
}
private boolean transform(String a, String b){
int diff = 0;
for(int i=0;i<a.length();i++){
if(a.charAt(i)!=b.charAt(i)){
diff++;
}
}
return diff == 1;
}
class Pair{
private String word;
private List<String> list;
public Pair(String word,List<String> list){
this.word = word;
this.list = list;
}
}
}
时间复杂度:
O
(
l
∗
w
2
)
O(l*w^2)
O(l∗w2) w是词的个数,l是词的长度。
在构建图的过程时间复杂度
O
(
l
∗
w
2
)
O(l*w^2)
O(l∗w2),bfs最坏时间复杂度是
O
(
w
2
)
O(w^2)
O(w2),两者取最大值:
O
(
l
∗
w
2
)
O(l*w^2)
O(l∗w2)