Problem Word Ladder

Problem Description:

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

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:

 1 public int ladderLength(String start, String end, Set<String> dict) {
 2         if (dict.size() == 0) {
 3             return 0;
 4         }
 5 
 6         LinkedList<Integer> distanceQueue = new LinkedList<Integer>();
 7         LinkedList<String> wordQueue = new LinkedList<String>();
 8 
 9         wordQueue.add(start);
10         distanceQueue.add(1);
11 
12         while (! wordQueue.isEmpty()){
13             String currentword = wordQueue.pop();
14             int currentDistance = distanceQueue.pop();
15 
16             if (currentword.equals(end)) {
17                 return currentDistance;
18             }
19 
20 for (int i = 0; i < currentword.length(); i++) {
21                 char ch = currentword.charAt(i);
22 
23                 for (int c = 'a'; c <= 'z'; c++) {
24                     if (ch != c) {
25                         char[] charArray = currentword.toCharArray();
26                         charArray[i] = (char)c;
27                         String newWord = new String (charArray);
28 
29                         if (dict.contains(newWord)) {
30                             wordQueue.add(newWord);
31                             distanceQueue.add(currentDistance + 1);
32                             dict.remove(newWord);
33                         }
34                     }
35                 }
36             }
37         }
38 
39         return 0;
40     }

 

posted @ 2014-06-29 14:54  HaruHaru  阅读(184)  评论(0编辑  收藏  举报