Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
Solution (Double direct BFS):
1 public class Solution { 2 public int ladderLength(String start, String end, Set<String> dict) { 3 //Double direct BFS 4 List<String> list1 = new ArrayList<String>(); 5 Map<String,Integer> set1 = new HashMap<String,Integer>(); 6 List<String> list2 = new ArrayList<String>(); 7 Map<String,Integer> set2 = new HashMap<String,Integer>(); 8 int index1 = 0; 9 int index2 = 0; 10 list1.add(start); 11 list2.add(end); 12 set1.put(start,1); 13 set2.put(end,1); 14 String curStr1, curStr2; 15 String interStr=""; 16 while (true){ 17 boolean find = false; 18 19 //No solution 20 if (index1>=list1.size()) 21 return 0; 22 23 curStr1 = list1.get(index1); 24 for (int i=0;i<curStr1.length();i++){ 25 char array[] = curStr1.toCharArray(); 26 for (array[i]='a';array[i]<='z';array[i]++){ 27 String temp = new String(array); 28 if (set1.containsKey(temp)) continue; 29 if (dict.contains(temp)){ 30 list1.add(temp); 31 set1.put(temp,set1.get(curStr1)+1); 32 33 if (set2.containsKey(temp)){ 34 interStr = temp; 35 find = true; 36 break; 37 } 38 } 39 } 40 } 41 index1++; 42 if (find) 43 break; 44 45 if (index2>=list2.size()) 46 return 0; 47 48 curStr2 = list2.get(index2); 49 for (int i=0;i<curStr2.length();i++){ 50 char array[] = curStr2.toCharArray(); 51 for (array[i]='a';array[i]<='z';array[i]++){ 52 String temp = new String(array); 53 if (set2.containsKey(temp)) continue; 54 if (dict.contains(temp)){ 55 list2.add(temp); 56 set2.put(temp,set2.get(curStr2)+1); 57 58 if (set1.containsKey(temp)){ 59 interStr = temp; 60 find = true; 61 break; 62 } 63 } 64 } 65 } 66 67 68 index2++; 69 if (find) 70 break; 71 } 72 73 74 //Add path from pos direct 75 int dis = 0; 76 dis += set1.get(interStr); 77 dis += set2.get(interStr); 78 dis--; 79 80 return dis; 81 } 82 83 84 85 }