Word Ladder II

73 篇文章 0 订阅

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

Return

  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]

Note:

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

思路1:跟Word Ladder I很类似,就是用hashmap<String, List<List<String>> 每一层,每一个word,后面跟一个path,从上面来的path,然后如果是end,就输出最后的path;这个写法很巧妙,有点像滚动数组;Time: O(V + E) = O(length of wordList + connections);

class Solution {
    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        List<List<String>> lists = new ArrayList<List<String>>();
        HashSet<String> dict = new HashSet<String>(wordList);
        if(!dict.contains(endWord)) {
            return lists;
        }
        
        HashMap<String, List<List<String>>> layer = new HashMap<>();
        layer.putIfAbsent(beginWord, new ArrayList<>());
        layer.get(beginWord).add(new ArrayList<>(Arrays.asList(beginWord)));
        
        while(!layer.isEmpty()) {
            HashMap<String, List<List<String>>> newlayer = new HashMap<>();
            for(String word: layer.keySet()) {
                // find it;
                if(word.equals(endWord)) {
                    return layer.get(endWord);
                }
                for(String neighbor: getAllNeighbor(word, dict)) {
                    newlayer.putIfAbsent(neighbor, new ArrayList<List<String>>());
                    for(List<String> list: layer.get(word)) {
                        List<String> newlist = new ArrayList<String>(list);
                        newlist.add(neighbor);
                        newlayer.get(neighbor).add(newlist);
                    }
                }
            }
            layer = newlayer;
            // remove newlayer key to prevent duplicate;
            for(String key: newlayer.keySet()) {
                dict.remove(key);    
            }
        }
        return lists;
    }
    
    private List<String> getAllNeighbor(String word, HashSet<String> dict) {
        List<String> list = new ArrayList<String>();
        char[] ss = word.toCharArray();
        for(int i = 0; i < ss.length; i++) {
            char origin = ss[i];
            for(char c = 'a'; c <= 'z'; c++) {
                if(c == origin) {
                    continue;
                }
                ss[i] = c;
                String newstr = new String(ss);
                if(dict.contains(newstr)) {
                    list.add(newstr);
                }
            }
            ss[i] = origin;
        }
        return list;
    }
}

思路2:首先用bfs去traverse 图,从end开始,往start走,建立图,并且最重要的是记录所有点到end的距离,然后之后从start开始走的时候,就往distance小的方向走(也就是往distance-1的方向走),大的方向跳过,这样收集到的就是shortest path。

class Solution {
    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        List<List<String>> lists = new ArrayList<List<String>>();
        HashSet<String> dict = new HashSet<String>(wordList);
        if(!dict.contains(endWord)) {
            return lists;
        }
        dict.add(beginWord);
        dict.add(endWord);
        
        // build graph with distance;
        HashMap<String, Integer> distanceMap = new HashMap<>();
        HashMap<String, List<String>> graph = new HashMap<>();
        bfs(endWord, distanceMap, dict, graph);
        
        // collect path;
        List<String> list = new ArrayList<String>();
        dfs(graph, beginWord, endWord, distanceMap, list, lists);
        
        return lists;
    }
    
    private void dfs(HashMap<String, List<String>> graph, String start, String end,
                    HashMap<String, Integer> distanceMap, 
                    List<String> list,List<List<String>> lists) {
        if(start.equals(end)) {
            list.add(end);
            lists.add(new ArrayList<String>(list));
            list.remove(list.size() - 1);
            return;
        } else {
            list.add(start);
            for(String neighbor: graph.get(start)) {
                if(distanceMap.get(start) == distanceMap.get(neighbor) + 1) {
                    dfs(graph, neighbor, end, distanceMap, list, lists);
                }
            }
            list.remove(list.size() - 1);
        }
    }
    
    private void bfs(String start, HashMap<String, Integer> distanceMap,
                    HashSet<String> dict, HashMap<String, List<String>> graph) {
        Queue<String> queue = new LinkedList<String>();
        queue.offer(start);
        distanceMap.put(start, 1);
        for(String word: dict) {
            graph.put(word, new ArrayList<String>());
        }
        
        while(!queue.isEmpty()) {
            String node = queue.poll();
            for(String neighbor: getAllNeighbors(node, dict)) {
                // build graph;
                graph.get(node).add(neighbor);
                // populate distanceMap;
                if(!distanceMap.containsKey(neighbor)) {
                    distanceMap.put(neighbor, distanceMap.get(node) + 1);
                    queue.offer(neighbor);
                }
            }
        }
    }
    
    private List<String> getAllNeighbors(String start, HashSet<String> dict) {
        List<String> list = new ArrayList<String>();
        char[] ss = start.toCharArray();
        for(int i = 0; i < ss.length; i++) {
            char origin = ss[i];
            for(char c = 'a'; c <= 'z'; c++) {
                if(origin == c) {
                    continue;
                }
                ss[i] = c;
                String neighbor = new String(ss);
                if(dict.contains(neighbor)) {
                    list.add(neighbor);
                }
                ss[i] = origin;
            }
        }
        return list;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值