描述
給出兩個單詞(start和end)和一個字典,找出所有從start到end的最短轉換序列
比如:
1.每次只能改變一個字母。
2.變換過程中的中間單詞必須在字典中出現。
注意事項
1.所有單詞具有相同的長度。
2.所有單詞都只包含小寫字母。
樣例
給出數據如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
返回
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
思路
先從end出發做start的BFS,再從start出發做end的DFS,一邊走一邊保證距離越來越近,也可以倒過來做因為是無向圖,所以只需要保證路徑順序就可以了,一個方向BFS另一個方向DFS
代碼
public class Solution {
public List<List<String>> findLadders(String start,
String end,
Set<String> dict) {
List<List<String>> ladders = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
Map<String, Integer> distance = new HashMap<String, Integer>();
dict.add(start);
dict.add(end);
bfs(map, distance, start, end, dict);
List<String> path = new ArrayList<String>();
dfs(path, map, distance, end, start, ladders);
return ladders;
}
// 從起點開始進行bfs,bfs對map和distance都進行了初始化
private void bfs(Map<String, List<String>> map,
Map<String, Integer> distance,
String start,
String end,
Set <String> dict) {
Queue<String> queue = new LinkedList<String>();
queue.offer(start);
distance.put(start, 0);
// 給dict中每一個單詞映射一個新的hash數組
for (String s : dict) {
map.put(s, new ArrayList<String>());
}
while(!queue.isEmpty()) {
String crt = queue.poll();
List<String> nextList = getNextList(crt, dict);
for (String next : nextList) {
// 將當前單詞加入到下一個單詞的地圖中
map.get(next).add(crt);
// distance中未標記的結點,在distance中標好距離,加入隊列
if (!distance.containsKey(next)) {
distance.put(next, distance.get(crt) + 1);
queue.offer(next);
}
}
}
}
// 將當前單詞變為字典中存在的下一個單詞(兩個單詞差一個字母),將從起點到終點一條路線上的所有單詞全部加入到list
private List<String> getNextList(String crt, Set<String> dict) {
List<String> list = new ArrayList<String>();
for (char c = 'a'; c <= 'z'; c++) {
for (int i = 0; i < crt.length(); i++) {
if (c != crt.charAt(i)) {
String nextWord = crt.substring(0, i) + c
+ crt.substring(i + 1);
if (dict.contains(nextWord)) {
list.add(nextWord);
}
}
}
}
return list;
}
// 注意起始位置的變換要體現在接口參數中,從終點開始進行dfs,crt代表的是隊列中拋出的點,bfs運行到最后crt代表的是終點
private void dfs(List<String> path,
Map<String, List<String>> map,
Map<String, Integer> distance,
String crt,
String start,
List<List<String>> ladders) {
// crt是從end開始搜索的,所以當crt為start的時候,一條逆序的有效的路徑已經出來了,那么這里把這條路徑翻轉一下,放到結果中,之后再翻轉一下以便之后其他路徑的搜索
// 不可以把path.add(crt)加入到else里,因為每次遞歸都要remove,若寫進else里并不會每次都把crt加入path,會造成動態數組下標越界
path.add(crt);
if (crt.equals(start)) {
Collections.reverse(path);
ladders.add(new ArrayList(path));
// 若不翻轉回來的話,當退出一層dfs,執行完path.remove(path.size() - 1);會移除錯誤的單詞
Collections.reverse(path);
} else {
for (String next : map.get(crt)) {
// 注意此處不是distance.get(next) == distance.get(crt) + 1,對下一個計算的單詞要求是要distance里(并不是每個單詞都在distance里)然后距離只有+1的差距
if (distance.containsKey(next) && distance.get(crt) == distance.get(next) + 1) {
dfs(path, map, distance, next, start, ladders);
}
}
}
path.remove(path.size() - 1);
}
}