Word Ladder 改

要求输入最短路径的长度 和 最短路径的个数。。。

比如 axy - bxy - dxz

      axy - cxy - dxz

长度为3, 个数 为2.

 

 1 public class Solution {
 2     public int ladderLength(String start, String end, HashSet<String> dict) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int len = start.length();
 6         int count = 0;
 7         HashSet<String> used = new HashSet<String>(); 
 8         HashSet<String> pred = new HashSet<String>();
 9         if(len != end.length()) return -1;
10         if(len == 0) return 0;
11         Queue<String> queue = new LinkedList<String>();
12 
13         queue.add(start);
14         used.add(start);
15         pred.add(start);
16         int pre = 1;
17         int next = 0;
18         int flag = 0;
19         while(!queue.isEmpty()){
20             String cur = queue.poll();
21             for(int i = 0; i < len; i ++){
22                 for(char c = 'a'; c < 'z' + 1; c ++){
23                     if(c == cur.charAt(i)) continue;
24                     char[] ts = cur.toCharArray();
25                     ts[i] = c;
26                     String test = String.valueOf(ts);
27                     if(dict.contains(test)){
28                         if(!pred.contains(test)){
29                             if(pre != 0){
30                                 next ++;
31                             }
32                             if(!used.contains(test))
33                                 used.add(test);
34                             queue.add(test);
35                         }
36                         if(test.equals(end)){
37                             flag = 1;
38                         }
39                     }
40                 }
41             }
42             pre --;
43             if(pre == 0){
44                 pre = next;
45                 pred = used;
46                 next = 0;
47                 count ++;
48                 if(flag == 1){
49                     break;
50                 }
51             }
52         }
53         if(flag == 1)
54             return count + 1;
55         return 0;
56     }
57 }

对于现在这一层, 只禁止它访问上一层和更之前访问过的点,而不禁止他访问本层访问过的点 即可。 使用两个set。

posted on 2013-04-17 08:13  Step-BY-Step  阅读(171)  评论(0编辑  收藏  举报

导航