Word Ladder II

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.

和word ladder I一样,采用BFS + recurise来做。

 1 public class Solution {
 2     int len;
 3     int count;
 4     boolean sig;
 5     ArrayList<ArrayList<String>> result;
 6     HashSet<String> used;
 7     LinkedList<String> queue;
 8     String end;
 9     HashSet<String> dict;
10     public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict) {
11         // Start typing your Java solution below
12         // DO NOT write main() function
13         len = start.length();
14         count = 0;
15         sig = false;
16         result = new ArrayList<ArrayList<String>>();
17         used = new HashSet<String>();
18         this.end = end;
19         this.dict = dict;
20         queue = new LinkedList<String>();
21         queue.add(start);
22         queue.add("-1");
23         if(len != end.length() || len == 0) return result;
24         ArrayList<String> row = new ArrayList<String>();
25         row.add(start);
26         getRows(row);
27         return result;
28     }
29     public void getRows(ArrayList<String> row){
30         if(queue.size() != 1){
31             String cur = queue.poll();
32             if(cur.equals("-1")){
33                 if(sig) return;
34                 count ++;
35                 queue.add("-1");
36             }else{
37                 used.add(cur);
38                 for(int i = 0; i < len; i ++)
39                     for(char c = 'a'; c < 'z' + 1; c ++){
40                         if(c == cur.charAt(i)) continue;
41                         char[] ts = cur.toCharArray();
42                         ts[i] = c;
43                         String test = String.valueOf(ts);
44                         if(dict.contains(test) && !used.contains(test)){
45                             used.add(test);
46                             queue.add(test);
47                         }
48                         if(test.equals(end)){ 
49                             row.add(end); 
50                             result.add(row);
51                             return;
52                         }
53                         ArrayList<String> rowa = new ArrayList<String>(row);
54                         rowa.add(test);
55                         getRows(rowa);
56                 }
57             }
58         }
59     }
60 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3460706.html