题目

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

  1. [
  2. ["hit","hot","dot","dog","cog"],
  3. ["hit","hot","lot","log","cog"]
  4. ]

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

    Python文件相关操作 打开文件 打开文件,采用open方法,会将文件的句柄返回,如下: f = open('test_file.txt','r',encoding='utf-8') 在上面的代码中 ...

  2. poj 1511 优先队列优化dijkstra *

    题意:两遍最短路 链接:点我 注意结果用long long #include<cstdio> #include<iostream> #include<algorithm& ...

  3. Spring MVC如何接收浏览器传递来的请求参数--request--形参--实体类封装

    阅读目录 1. 通过HttpServletRequest获得请求参数和数据 2. 处理方法形参名==请求参数名 3. 如果形参名跟请求参数名不一样怎么办呢?用@RequestParam注解 4. 用实 ...

  4. SNMP代理软件开发

    SNMP代理模块包括6个子模块: SNMP协议主要有五种报文get.get-next.set.get-response,trap.l.get-request操作:从代理进程处提取一个或多个参数值2.g ...

  5. 中国移动CMPP协议、联通SGIP协议、电信SMGP协议短信网关

    移动cmpp协议 英文缩写:CMPP (China Mobile Peer to Peer) 中文名称:中国移动通信互联网短信网关接口协议 说明:为中国移动通信集团公司企业规范.规范中描述了中国移动短 ...

  6. J-Link Version

    "J-Link / Flasher Portable V1 " "J-Link ARM / Flasher ARM V2 " "J-Link ARM ...

  7. MongoDB+MongoVUE安装及入门

    前言及概念 据说nodejs和mongoDB是一对好基友,于是就忍不住去学习了解了一下MongoDB相关的一些东西, 那么,MongoDB是什么?这里的五件事是每个开放人员应该知道的: MongoDB ...

  8. What is the largest TCP/IP network port number allowable for IPv4

    69 down vote The largest port number is an unsigned short 2^16-1: 65535 A registered port is one ass ...

  9. Unity3D实践系列07,组件的启用或禁用开关,物体的的可见或不可见开关,以及相应事件

    创建一个Unity项目. 在"Project"窗口中,在"Asserts"中,添加"_MyScene"文件夹. 点击"File&q ...

  10. Maven 构建

    最近在工作中越来越经常的用到了Maven作为项目管理和Jar包管理和构建的工具,感觉Maven的确是很好用的.而且要将Maven的功能最大发挥出来,多模块是一个很好的集成例子. 一个Maven项目包括 ...