126. Word Ladder II

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.
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.
Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output:
[
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
]
Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: []

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

本题解法主要是构建一个endWord到beginWord的距离最短的单向图,然后使用回溯法得到所有答案。

public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        List<List<String>> ans = new ArrayList<>();
        if(wordList.size() == 0) return ans;

        //首先构建一个从从endWord到beginWord的图(只构建路径最短的)
        int min = Integer.MAX_VALUE;//min表示从beginWord到endWord的最短路径距离
        Map<String, List<String>> graph = new HashMap<>();//从beginWord到endWord的图
        Map<String, Integer> distance = new HashMap<>();//表示从beginWord出发后走的距离(没经过一个word,距离加1)
        for(String str : wordList) {//初始化
            distance.put(str, Integer.MAX_VALUE);
        }
        distance.put(beginWord, 0);
        Queue<String> queue = new ArrayDeque<>();//用队列来实现BFS以构建图
        queue.add(beginWord);
        while(!queue.isEmpty()) {
            String word = queue.poll();
            int step = distance.get(word) + 1;//表示到达endWord已经经过的距离
            if(step > min) {//如果step超过到达endWord的距离,则不将此节点加进图里
                break;
            }
            //对word每个位置的字母进行替换来BFS
            for(int i = 0; i < word.length(); ++i) {
                StringBuilder sb = new StringBuilder(word);
                for(char ch = 'a'; ch <= 'z'; ++ch) {
                    sb.setCharAt(i, ch);
                    String newWord = sb.toString();
                    if(distance.containsKey(newWord)) {
                        if(step > distance.get(newWord)) {//不是到达endWord的最短路径
                            continue;
                        } else if(step < distance.get(newWord)) {
                            queue.add(newWord);
                            distance.put(newWord, step);
                        } else ;//表示该word重复变换成自己,不需处理
                        if(graph.containsKey(newWord)) {//构建单向图(反向构建,从endWord到beginWord)
                            graph.get(newWord).add(word);
                        } else {
                            List<String> list = new LinkedList<>();
                            list.add(word);
                            graph.put(newWord, list);
                        }
                        if(newWord.equals(endWord)) {//刷新从endWord到beginWord的最短距离
                            min = step;
                        }
                    }
                }
            }
        }

        //使用回溯来获取结果
        LinkedList<String> current = new LinkedList<>();
        backTracking(endWord, beginWord, current, ans, graph);
        return ans;
    }

    private void backTracking(String word, String beginWord, List<String> current, List<List<String>> ans, Map<String, List<String>> graph) {
        if(word.equals(beginWord)) {
            current.add(0, word);
            ans.add(new ArrayList<>(current));
            current.remove(0);
            return;
        }
        current.add(0, word);
        if(graph.get(word) != null) {
            for(String str : graph.get(word)) {
                backTracking(str, beginWord, current, ans, graph);
            }
        }
        current.remove(0);
    }

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值