题目

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.

题解

答案是http://www.1point3acres.com/bbs/thread-51646-1-1.html 上面
iostreamin写的。

我就直接贴过来就好,这道题多读读代码看明白。

代码:

  1    public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict) {  
  2           
  3         HashMap<String, HashSet<String>> neighbours = new HashMap<String, HashSet<String>>();  
  4           
  5         dict.add(start);  
  6         dict.add(end);  
  7           
  8         // init adjacent graph          
  9         for(String str : dict){  
 10             calcNeighbours(neighbours, str, dict);  
 11         }  
 12           
 13         ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();  
 14           
 15         // BFS search queue  
 16         LinkedList<Node> queue = new LinkedList<Node>();  
 17         queue.add(new Node(null, start, 1)); //the root has not parent and its level == 1 
 18           
 19         // BFS level  
 20         int previousLevel = 0;  
 21           
 22         // mark which nodes have been visited, to break infinite loop  
 23         HashMap<String, Integer> visited = new HashMap<String, Integer>();   
 24         while(!queue.isEmpty()){  
 25             Node n = queue.pollFirst();              
 26             if(end.equals(n.str)){   
 27                 // fine one path, check its length, if longer than previous path it's valid  
 28                 // otherwise all possible short path have been found, should stop  
 29                 if(previousLevel == 0 || n.level == previousLevel){  
 30                     previousLevel = n.level;  
 31                     findPath(n, result);                      
 32                 }else {  
 33                     // all path with length *previousLevel* have been found  
 34                     break;  
 35                 }                  
 36             }else {  
 37                 HashSet<String> set = neighbours.get(n.str);                   
 38                   
 39                 if(set == null || set.isEmpty()) continue;  
 40                 // note: I'm not using simple for(String s: set) here. This is to avoid hashset's  
 41                 // current modification exception.  
 42                 ArrayList<String> toRemove = new ArrayList<String>();  
 43                 for (String s : set) {  
 44                       
 45                     // if s has been visited before at a smaller level, there is already a shorter   
 46                     // path from start to s thus we should ignore s so as to break infinite loop; if   
 47                     // on the same level, we still need to put it into queue.  
 48                     if(visited.containsKey(s)){  
 49                         Integer occurLevel = visited.get(s);  
 50                         if(n.level+1 > occurLevel){  
 51                             neighbours.get(s).remove(n.str);  
 52                             toRemove.add(s);  
 53                             continue;  
 54                         }  
 55                     }  
 56                     visited.put(s,  n.level+1);  
 57                     queue.add(new Node(n, s, n.level + 1));  
 58                     if(neighbours.containsKey(s))  
 59                         neighbours.get(s).remove(n.str);  
 60                 }  
 61                 for(String s: toRemove){  
 62                     set.remove(s);  
 63                 }  
 64             }  
 65         }  
 66   
 67         return result;  
 68     }  
 69       
 70     public void findPath(Node n, ArrayList<ArrayList<String>> result){  
 71         ArrayList<String> path = new ArrayList<String>();  
 72         Node p = n;  
 73         while(p != null){  
 74             path.add(0, p.str);  
 75             p = p.parent;   
 76         }  
 77         result.add(path);  
 78     }  
 79   
 80     /* 
 81      * complexity: O(26*str.length*dict.size)=O(L*N) 
 82      */  
 83     void calcNeighbours(HashMap<String, HashSet<String>> neighbours, String str, HashSet<String> dict) {  
 84         int length = str.length();  
 85         char [] chars = str.toCharArray();  
 86         for (int i = 0; i < length; i++) {  
 87               
 88             char old = chars[i];   
 89             for (char c = 'a'; c <= 'z'; c++) {  
 90   
 91                 if (c == old)  continue;  
 92                 chars[i] = c;  
 93                 String newstr = new String(chars);                  
 94                   
 95                 if (dict.contains(newstr)) {  
 96                     HashSet<String> set = neighbours.get(str);  
 97                     if (set != null) {  
 98                         set.add(newstr);  
 99                     } else {  
                         HashSet<String> newset = new HashSet<String>();  
                         newset.add(newstr);  
                         neighbours.put(str, newset);  
                     }  
                 }                  
             }  
             chars[i] = old;  
         }  
     }  
       
     private class Node {  
         public Node parent;  //previous node
         public String str;  
         public int level;  
         public Node(Node p, String s, int l){  
             parent = p;  
             str = s;  
             level = l;  
         }  
     } 
 Reference:http://www.1point3acres.com/bbs/thread-51646-1-1.html

Word Ladder II leetcode java的更多相关文章

  1. Word Break II leetcode java

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  2. Word Ladder II [leetcode]

    本题有几个注意点: 1. 回溯找路径时.依据路径的最大长度控制回溯深度 2. BFS时,在找到end单词后,给当前层做标记find=true,遍历完当前层后结束.不须要遍历下一层了. 3. 能够将字典 ...

  3. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  4. LeetCode: Word Ladder II 解题报告

    Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...

  5. [Leetcode Week5]Word Ladder II

    Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...

  6. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

  7. LeetCode :Word Ladder II My Solution

    Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start  ...

  8. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  9. 126. Word Ladder II(hard)

    126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...

随机推荐

  1. 我的php.ini上传文件配置

    可以通过phpinfo查看.当前的配置信息 # php -i | grep php.ini              //查看php.ini位置 file_uploads = on          ...

  2. SPFA算法 O(kE)

    主要思想是:     初始时将起点加入队列.每次从队列中取出一个元素,并对所有与它相邻的点进行修改,若某个相邻的点修改成功,则将其入队.直到队列为空时算法结束.     这个算法,简单的说就是队列优化 ...

  3. 二分法(折半查找法)小demo

    使用此算法,必须有一个前提,那就是数组必须是有序的. package com.ly.tcwireless.international.test; import org.junit.Test; publ ...

  4. Golang 处理 Json(二):解码

    golang 编码 json 还比较简单,而解析 json 则非常蛋疼.不像 PHP 一句 json_decode() 就能搞定.之前项目开发中,为了兼容不同客户端的需求,请求的 content-ty ...

  5. hdu1242 Rescue(BFS +优先队列 or BFS )

    http://acm.hdu.edu.cn/showproblem.php?pid=1242 题意:     Angel被传说中神秘的邪恶的Moligpy人抓住了!他被关在一个迷宫中.迷宫的长.宽不超 ...

  6. C#中泛型容器Stack<T>的用法,以及借此实现”撤销/重做”功能

    .Net为我们提供了众多的泛型集合.比如,Stack<T>先进后出,Queue<T>先进先出,List<T>集合元素可排序,支持索引,LinkedList<T ...

  7. Spring Boot 2.0 + zipkin 分布式跟踪系统快速入门

    原文:https://www.jianshu.com/p/9bfe103418e2 注意 Spring Boot 2.0之后,使用EnableZipkinServer创建自定义的zipkin服务器已经 ...

  8. IOS-plist文件DES加密

    转载请说明出处:http://www.cnblogs.com/gexun/p/3705207.html,谢谢. 这些天一直在做一个知识问答的项目,因为初赛的项目题目比较少,所以题目就写在本地的plis ...

  9. arcgis10.5.1 对齐要素

    许可级别:BasicStandardAdvanced 摘要 标识地理处理工具用于标识搜索距离中输入要素与目标要素的不一致部分并使其与目标要素一致. 插图 用法 警告: 此工具用于修改输入数据.有关详细 ...

  10. 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作

    spring boot 2.X集成ES 进行CRUD操作  完整版 内容包括: ============================================================ ...