Word Ladder(LintCode)

Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence 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
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.

 

用BFS做,字符串只相差一个字符的就当作有边。

 1 public class Solution {
 2     /**
 3       * @param start, a string
 4       * @param end, a string
 5       * @param dict, a set of string
 6       * @return an integer
 7       */
 8     public int ladderLength(String start, String end, Set<String> dict) {
 9         Queue q = new LinkedList();
10         dict.add(end);
11         int reslut = 0;
12         
13         //转成List方便标记,其实也可以将搜索过的String从Set中移除
14         List<String> list = new ArrayList<String>(dict);
15         int[] flag = new int[list.size()];
16         q.add(start);
17         int n = 1;
18         int x = 0;
19         while(q.size() > 0) {
20             String y = (String)q.remove();
21             n--;
22             for (int i = 0;i<list.size() ;i++ ) {
23                 if(end.equals(y)) return reslut+1;
24                 if (judge(list.get(i),y) == 1 && flag[i] == 0) {
25                     x++;
26                     q.add(list.get(i));
27                     flag[i] = 1;
28                 }
29             }
30             if (n == 0) {
31                 n = x;
32                 x = 0;
33                 reslut++;
34             }
35         }
36 
37         return 0;
38     }
39 
40     public int judge(String a,String b) {
41         int num = 0;
42         char[] acs = a.toCharArray();
43         char[] bcs = b.toCharArray();
44         for (int i = 0;i<acs.length ;i++ ) {
45             if(acs[i] != bcs[i]) num++;
46         }
47         return num;
48     }
49 }

 

posted @ 2015-12-12 16:26  -.-|  阅读(368)  评论(0编辑  收藏  举报