成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專(zhuān)欄INFORMATION COLUMN

[LeetCode] 126. Word Ladder II

wayneli / 1793人閱讀

摘要:存放過(guò)程中的所有集合為所有的結(jié)尾,則順序存放這個(gè)結(jié)尾對(duì)應(yīng)的中的所有存放同一個(gè)循環(huán)的新加入的,在下一個(gè)循環(huán)再依次對(duì)其中元素進(jìn)行進(jìn)一步的把首個(gè)字符串放入新,再將放入,并將鍵值對(duì)放入,進(jì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

Notice

All words have the same length.
All words contain only lowercase alphabetic characters.

Example

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 List> 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;
    }
}
Solution Note

result: 存放transformation過(guò)程中的所有List集合

map: key為所有transformation的結(jié)尾String,value則順序存放這個(gè)結(jié)尾String對(duì)應(yīng)的transformation中的所有String

queue: 存放同一個(gè)循環(huán)level的新加入的String,在下一個(gè)循環(huán)再依次對(duì)其中元素進(jìn)行進(jìn)一步的BFS

preList: 把首個(gè)字符串start放入新List,再將List放入res,并將start-res鍵值對(duì)放入map,進(jìn)行初始化

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)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/65014.html

相關(guān)文章

  • leetcode126. Word Ladder II

    摘要:題目要求相比于,要求返回所有的最短路徑。至于如何生成該有向圖,則需要通過(guò)廣度優(yōu)先算法,利用隊(duì)列來(lái)實(shí)現(xiàn)。將每一層的分別入棧。如果遇到則至該層結(jié)尾廣度優(yōu)先算法結(jié)束。通過(guò)這種方式來(lái)防止形成圈。 題目要求 Given two words (beginWord and endWord), and a dictionarys word list, find all shortest transfo...

    cooxer 評(píng)論0 收藏0
  • 126. Word Ladder II

    題目: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...

    Tangpj 評(píng)論0 收藏0
  • [Leetcode] Word Ladder 單詞爬梯

    摘要:另外,為了避免產(chǎn)生環(huán)路和重復(fù)計(jì)算,我們找到一個(gè)存在于字典的新的詞時(shí),就要把它從字典中移去。代碼用來(lái)記錄跳數(shù)控制來(lái)確保一次循環(huán)只計(jì)算同一層的節(jié)點(diǎn),有點(diǎn)像二叉樹(shù)遍歷循環(huán)這個(gè)詞從第一位字母到最后一位字母循環(huán)這一位被替換成個(gè)其他字母的情況 Word Ladder Given two words (beginWord and endWord), and a dictionary, find t...

    pinecone 評(píng)論0 收藏0
  • leetcode127. Word Ladder

    摘要:但是這種要遍歷所有的情況,哪怕是已經(jīng)超過(guò)最小操作次數(shù)的情況,導(dǎo)致代碼超時(shí)。其實(shí)從另一個(gè)角度來(lái)說(shuō),這道題可以看做是廣度優(yōu)先算法的一個(gè)展示。按上文中的題目為例,可以將廣度優(yōu)先算法寫(xiě)成以下形式。 題目要求 Given two words (beginWord and endWord), and a dictionarys word list, find the length of short...

    Galence 評(píng)論0 收藏0
  • [LeetCode/LintCode] Word Ladder

    摘要:使用,利用其按層次操作的性質(zhì),可以得到最優(yōu)解。這樣可以保證這一層被完全遍歷。每次循環(huán)取出的元素存為新的字符串。一旦找到和相同的字符串,就返回轉(zhuǎn)換序列長(zhǎng)度操作層數(shù),即。 Problem Given two words (start and end), and a dictionary, find the length of shortest transformation sequence...

    張金寶 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<