摘要:存放過程中的所有集合為所有的結(jié)尾,則順序存放這個結(jié)尾對應的中的所有存放同一個循環(huán)的新加入的,在下一個循環(huán)再依次對其中元素進行進一步的把首個字符串放入新,再將放入,并將鍵值對放入,進行初始化
Problem
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
All words have the same length.
All words contain only lowercase alphabetic characters.
Given:
start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]Solution DFS+BFS Updated 2018-11
class Solution { public ListSolution Note> findLadders(String start, String end, List
wordList) { List > res = new ArrayList<>(); Set
dict = new HashSet<>(wordList); if (!dict.contains(end)) return res; //save shortest distance from start to each node Map distanceMap = new HashMap<>(); //save all the nodes can be transformed from each node Map > neighborMap = new HashMap<>(); dict.add(start); //use bfs to: find the shortest distance; update neighborMap and distanceMap bfs(start, end, dict, neighborMap, distanceMap); //use dfs to: output all the paths with the shortest distance dfs(start, end, neighborMap, distanceMap, new ArrayList<>(), res); return res; } private void bfs(String start, String end, Set dict, Map > neighborMap, Map distanceMap) { for (String str: dict) { neighborMap.put(str, new ArrayList<>()); } Deque queue = new ArrayDeque<>(); queue.offer(start); distanceMap.put(start, 0); while (!queue.isEmpty()) { int size = queue.size(); boolean foundEnd = false; for (int i = 0; i < size; i++) { String cur = queue.poll(); int curDist = distanceMap.get(cur); List neighbors = getNeighbors(dict, cur); for (String neighbor: neighbors) { neighborMap.get(cur).add(neighbor); if (!distanceMap.containsKey(neighbor)) { distanceMap.put(neighbor, curDist+1); if (neighbor.equals(end)) foundEnd = true; else queue.offer(neighbor); } } } if (foundEnd) break; } } private void dfs(String start, String end, Map > neighborMap, Map distanceMap, List temp, List > res) { if (start.equals(end)) { temp.add(start); res.add(new ArrayList<>(temp)); temp.remove(temp.size()-1); } for (String neighbor: neighborMap.get(start)) { temp.add(start); if (distanceMap.get(neighbor) == distanceMap.get(start)+1) { dfs(neighbor, end, neighborMap, distanceMap, temp, res); } temp.remove(temp.size()-1); } } private List
getNeighbors(Set dict, String str) { List res = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { StringBuilder sb = new StringBuilder(str); for (char ch = "a"; ch <= "z"; ch++) { sb.setCharAt(i, ch); String neighbor = sb.toString(); if (dict.contains(neighbor)) res.add(neighbor); } } return res; } }
result: 存放transformation過程中的所有List
map: key為所有transformation的結(jié)尾String,value則順序存放這個結(jié)尾String對應的transformation中的所有String
queue: 存放同一個循環(huán)level的新加入的String,在下一個循環(huán)再依次對其中元素進行進一步的BFS
preList: 把首個字符串start放入新List,再將List放入res,并將start-res鍵值對放入map,進行初始化
public class Solution { public List> findLadders(String start, String end, Set
dict) { List > res = new ArrayList<>(); List
preList = new ArrayList<>(); Queue queue = new LinkedList<>(); Map >> map = new HashMap<>(); preList.add(start); queue.offer(start); res.add(preList); map.put(start, res); while (!queue.isEmpty()) { String pre = queue.poll(); if (pre.equals(end)) return map.get(pre); for (int i = 0; i < pre.length(); i++) { for (int j = 0; j < 26; j++) { StringBuilder sb = new StringBuilder(pre); sb.setCharAt(i,(char) ("a"+j)); String cur = sb.toString(); if (!cur.equals(pre) && dict.contains(cur) && (!map.containsKey(cur) || map.get(pre).get(0).size()+1 <= map.get(cur).get(0).size())) { List > temp = new ArrayList<>(); for (List
p: map.get(pre)) { List curList = new ArrayList<>(p); curList.add(cur); temp.add(curList); } if (!map.containsKey(cur)) { map.put(cur, temp); queue.offer(cur); } else if (map.get(pre).get(0).size()+1 < map.get(cur).get(0).size()) map.put(cur, temp); else map.get(cur).addAll(temp); } } } } return res.get(0).size() > 1 ? res : new ArrayList >(); } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/65014.html
摘要:題目要求相比于,要求返回所有的最短路徑。至于如何生成該有向圖,則需要通過廣度優(yōu)先算法,利用隊列來實現(xiàn)。將每一層的分別入棧。如果遇到則至該層結(jié)尾廣度優(yōu)先算法結(jié)束。通過這種方式來防止形成圈。 題目要求 Given two words (beginWord and endWord), and a dictionarys word list, find all shortest transfo...
題目:Given two words (beginWord and endWord), and a dictionarys word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a timeEach...
摘要:另外,為了避免產(chǎn)生環(huán)路和重復計算,我們找到一個存在于字典的新的詞時,就要把它從字典中移去。代碼用來記錄跳數(shù)控制來確保一次循環(huán)只計算同一層的節(jié)點,有點像二叉樹遍歷循環(huán)這個詞從第一位字母到最后一位字母循環(huán)這一位被替換成個其他字母的情況 Word Ladder Given two words (beginWord and endWord), and a dictionary, find t...
摘要:但是這種要遍歷所有的情況,哪怕是已經(jīng)超過最小操作次數(shù)的情況,導致代碼超時。其實從另一個角度來說,這道題可以看做是廣度優(yōu)先算法的一個展示。按上文中的題目為例,可以將廣度優(yōu)先算法寫成以下形式。 題目要求 Given two words (beginWord and endWord), and a dictionarys word list, find the length of short...
摘要:使用,利用其按層次操作的性質(zhì),可以得到最優(yōu)解。這樣可以保證這一層被完全遍歷。每次循環(huán)取出的元素存為新的字符串。一旦找到和相同的字符串,就返回轉(zhuǎn)換序列長度操作層數(shù),即。 Problem Given two words (start and end), and a dictionary, find the length of shortest transformation sequence...
閱讀 2187·2021-11-18 10:02
閱讀 3289·2021-11-11 16:55
閱讀 2694·2021-09-14 18:02
閱讀 2426·2021-09-04 16:41
閱讀 2056·2021-09-04 16:40
閱讀 1165·2019-08-30 15:56
閱讀 2213·2019-08-30 15:54
閱讀 3161·2019-08-30 14:15