算法细节系列(20):Word Ladder系列
算法細節(jié)系列(20):Word Ladder系列
詳細代碼可以fork下Github上leetcode項目,不定期更新。
題目摘自leetcode:
1. Leetcode 127: Word Ladder
2. Leetcode 126: Word Ladder II
Leetcode 127: Word Ladder
Problem:
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Example:
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
這道題其實不難,但要想到這種解法卻要費一番周折,如果對最短路徑搜索熟悉的話,相信你一眼就能看出答案了,并且我們要論證一點,為什么最短路徑算法對這道題來說是正確解法。
我的思路:
DFS,把所有編輯距離為1的單詞連接在一塊,構建一個MAP(鄰接矩陣)。這樣之后,我們就可以從beginWord開始DFS搜索了,中間需要狀態(tài)記錄。代碼如下:
代碼沒有多大問題,典型的DFS+狀態(tài)回溯,遍歷搜索每一條到達endWord的路徑,找尋最短路徑。但很可惜TLE了,直觀上來看是因為為了拿到到endWord的最短路徑,我們需要遍歷每一條到endWord的路徑,這是遞歸求解的一個特點。但實際情況,我們可以省去某些點的遍歷。
就那這個問題來說,如從beginWord開始搜索,如
beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"] wordList中編輯距離為1的單詞有: a. hot 此時BFS搜索與"hot"最近距離的單詞,有: a. dot b. lot 再BFS搜索"dot"時,有: a. cog 所以我們只需要BFS三次就能得到正確答案,而DFS中,需要DFS至少三次。上述過程就是經典的Dijkstra算法,代碼如下:
public int ladderLength(String beginWord, String endWord, List<String> wordList) {List<String> reached = new ArrayList<>();reached.add(beginWord);Set<String> wordSet = new HashSet<>(wordList);if(!wordSet.contains(endWord)) return 0;wordSet.add(endWord);int distance = 1;while (!reached.contains(endWord)){ //到達該目的地List<String> toAdd = new ArrayList<>();for (String each : reached){for (int i = 0; i < each.length(); i++){char[] chars = each.toCharArray();for (char c = 'a'; c <= 'z'; c++){chars[i] = c;String wd = new String(chars);if (wordSet.contains(wd)){toAdd.add(wd);wordSet.remove(wd); //記錄訪問狀態(tài)}}}}distance ++;if (toAdd.size() == 0) return 0; //沒有編輯距離為1的單詞reached = toAdd;}return distance;}Leetcode 126: Word Ladder II
Problem:
Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Example:
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
Return
[
[“hit”,”hot”,”dot”,”dog”,”cog”],
[“hit”,”hot”,”lot”,”log”,”cog”]
]
Note:
- Return an empty list if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
這道題的思路讓我對DFS和BFS有了一些基本理解,但還不夠深刻,咋說呢,我沒想到BFS和DFS還可以分工合作,BFS用來快速求出最小distance,而DFS則用來遍歷所有路徑,兩種遍歷方法各有長處,綜合起來就能解決該問題了,所以我寫了一個版本,代碼如下:
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {Map<String, List<String>> map = new HashMap<>();map.put(beginWord, new ArrayList<>());for (String word : wordList){map.put(word, new ArrayList<>());}for (String key : map.keySet()){List<String> container = map.get(key);for (String word : wordList){if (oneDiff(key, word)){container.add(word);}}map.put(key, container);}int distance = bfs(beginWord, endWord, wordList);List<List<String>> ans = new ArrayList<>();dfs(map, beginWord, endWord, ans, new ArrayList<>(), distance);return ans;}private void dfs(Map<String, List<String>> map,String beginWord, String endWord, List<List<String>> ans, List<String> path, int distance){path.add(beginWord);if (distance == 0){path.remove(path.size()-1); return;}if (beginWord.equals(endWord)){ans.add(new ArrayList<>(path));path.remove(path.size()-1);return;}for (String find : map.get(beginWord)){dfs(map, find, endWord, ans, path, distance-1);}path.remove(path.size()-1);}private int bfs(String beginWord, String endWord, List<String> wordList) {List<String> reached = new ArrayList<>();reached.add(beginWord);Set<String> wordSet = new HashSet<>(wordList);if(!wordSet.contains(endWord)) return 0;wordSet.add(endWord);int distance = 1;while (!reached.contains(endWord)){ //達到該目的地List<String> toAdd = new ArrayList<>();for (String each : reached){for (int i = 0; i < each.length(); i++){char[] chars = each.toCharArray();for (char c = 'a'; c <= 'z'; c++){chars[i] = c;String wd = new String(chars);if (wordSet.contains(wd)){toAdd.add(wd);wordSet.remove(wd);}}}}distance ++;if (toAdd.size() == 0) return 0;reached = toAdd;}return distance;}private boolean oneDiff(String a, String b){if (a.equals(b)) return false;char[] aa = a.toCharArray();char[] bb = b.toCharArray();int oneDiff = 0;for (int i = 0; i < aa.length; i++){if (aa[i] != bb[i]){oneDiff ++;if (oneDiff >= 2) return false;}}return true;}思路相當清楚了,以為能夠AC,結果發(fā)現(xiàn)TLE了,說明該題對時間的要求很高,從上述代碼我們也能發(fā)現(xiàn)一些基本問題,如BFS遍歷時可以構建MAP,而不用單獨構建MAP,非常耗時。其次,最關鍵的問題在于DFS,此版本的DFS沒有進行剪枝處理,剪枝能省去很多時間,所以我還需要對BFS進行改進。
思路:
首先,我們來看看上述代碼構建圖的一個模型,如下圖所示:
很明顯,如果我們對BFS沒有做任何限制,我們拿到的鄰接表一定是上述探頭斯,而此時如果用DFS進行搜索時,如從“hot”開始,它會搜索:
一條可能的搜索路徑: hot ---> dot ---> dog ---> cog 但與此同時DFS還會搜索路徑: hot ---> dot ---> tot ---> hot 上述路徑很明顯不需要DFS,但因為邊的相連,使得這種沒必要的搜索也將繼續(xù)。所以一個優(yōu)化點就在于,好馬不吃回頭草,存在環(huán)路的回頭草絕對不是達到endWord的最短路徑。很遺憾,鄰接表無法表示這種非環(huán)的圖,所以想法就是用一個Map<String,Integer>來記錄到達每個單詞的最短路徑,一旦map中有該單詞,就不再更新最短路徑(避免環(huán)路搜索)
所以BFS代碼如下:
private int bfs(String beginWord, String endWord, Set<String> wordDict, Map<String, Integer> distanceMap,Map<String, List<String>> map) {if (!wordDict.contains(endWord))return 0;map.put(beginWord, new ArrayList<>());for (String word : wordDict) {map.put(word, new ArrayList<>());}Queue<String> queue = new LinkedList<>();queue.offer(beginWord);distanceMap.put(beginWord, 1);while (!queue.isEmpty()) {int count = queue.size();boolean foundEnd = false;// 這種循環(huán)遍歷很有意思,看作一個整體for (int i = 0; i < count; i++) {String cur = queue.poll();int curDistance = distanceMap.get(cur);List<String> neighbors = getNeighbors(cur, wordDict);if (neighbors.size() == 0)return 0;for (String neighbor : neighbors) {map.get(cur).add(neighbor);//存在環(huán)的情況,不去更新最短路徑if (!distanceMap.containsKey(neighbor)) {distanceMap.put(neighbor, curDistance + 1);if (endWord.equals(neighbor)) {foundEnd = true;} else {queue.offer(neighbor);}}}}//一旦抵到了endWord,我們就放棄建立后續(xù)的圖if (foundEnd)break;}return distanceMap.get(endWord);}上述代碼在BFS時,與endWord無關的那些結點都丟棄掉了,且解決了有環(huán)路的情況。圖結構如下所示:
這樣在DFS構建路徑時,它的速度就比原先要快得多。在BFS中還需要注意一個函數(shù)【getNeighbors()】,剛開始我寫的這版程序也超時了,苦思許久都找不到原因,后來才發(fā)現(xiàn)是getNeighbors的玄機,它在建立鄰接表時,一定要使用【HashSet】的搜索方法,而不要用原生的【List】的搜索方法。
所以完整代碼如下:
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {Map<String, List<String>> map = new HashMap<>();Map<String, Integer> distanceMap = new HashMap<>();Set<String> wordDict = new HashSet<>(wordList);wordDict.add(beginWord);int distance = bfs(beginWord, endWord, wordDict, distanceMap, map);List<List<String>> ans = new ArrayList<>();if (distance == 0)return ans;dfs(map, beginWord, endWord, ans, new ArrayList<>(), distance, distanceMap);return ans;}private void dfs(Map<String, List<String>> map, String beginWord, String endWord, List<List<String>> ans,List<String> path, int distance, Map<String, Integer> distanceMap) {path.add(beginWord);if (distance == 0) {path.remove(path.size() - 1);return;}if (beginWord.equals(endWord)) {ans.add(new ArrayList<>(path));path.remove(path.size() - 1);return;}for (String find : map.get(beginWord)) {if (!distanceMap.containsKey(find))continue;if (distanceMap.get(beginWord) + 1 == distanceMap.get(find))dfs(map, find, endWord, ans, path, distance - 1, distanceMap);}path.remove(path.size() - 1);}private int bfs(String beginWord, String endWord, Set<String> wordDict, Map<String, Integer> distanceMap,Map<String, List<String>> map) {if (!wordDict.contains(endWord))return 0;map.put(beginWord, new ArrayList<>());for (String word : wordDict) {map.put(word, new ArrayList<>());}Queue<String> queue = new LinkedList<>();queue.offer(beginWord);distanceMap.put(beginWord, 1);while (!queue.isEmpty()) {int count = queue.size();boolean foundEnd = false;for (int i = 0; i < count; i++) {String cur = queue.poll();int curDistance = distanceMap.get(cur);List<String> neighbors = getNeighbors(cur, wordDict);if (neighbors.size() == 0)return 0;for (String neighbor : neighbors) {map.get(cur).add(neighbor);if (!distanceMap.containsKey(neighbor)) {distanceMap.put(neighbor, curDistance + 1);if (endWord.equals(neighbor)) {foundEnd = true;} else {queue.offer(neighbor);}}}}if (foundEnd)break;}return distanceMap.get(endWord);}private List<String> getNeighbors(String word, Set<String> wordList) {List<String> ans = new ArrayList<>();for (int i = 0; i < word.length(); i++) {char[] cc = word.toCharArray();for (char c = 'a'; c <= 'z'; c++) {cc[i] = c;String newWord = new String(cc);if (wordList.contains(newWord)) {if (newWord.equals(word))continue;ans.add(newWord);}}}return ans;}DFS是一個典型的回溯+剪枝的遞歸方法,凡是函數(shù)返回的地方,我們都需要進行狀態(tài)還原,注意再注意。
總結
以上是生活随笔為你收集整理的算法细节系列(20):Word Ladder系列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript基础:元素增删改操作
- 下一篇: 将一元人民币兑换成1分、2分、5分,有几