127. Word Ladder

相当于bfs

 1     public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
 2         if(beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() != beginWord.length() || wordList == null) {
 3             return 0;
 4         }
 5         Set<String> visited = new HashSet<String>();
 6         visited.add(beginWord);
 7         wordList.add(endWord);
 8         int length = 1;
 9         while(!visited.contains(endWord)) {
10             length++;
11             Set<String> currentWord = new HashSet<String>();
12             for(String word: visited) {
13                 for(int i = 0; i < word.length(); i++) {
14                     for(char j = 'a'; j <= 'z'; j++) {
15                         char[] wordArr = word.toCharArray();
16                         wordArr[i] = j;
17                         String curWord = new String(wordArr);
18                         if(!curWord.equals(word) && wordList.contains(curWord)) {
19                             currentWord.add(curWord);
20                             wordList.remove(curWord);
21                         }
22                     }
23                 }
24             }
25             if(currentWord.isEmpty()) {
26                 return 0;
27             }
28             visited  = currentWord;
29         }
30         return length;
31     }

 

posted @ 2016-06-15 07:49  warmland  阅读(117)  评论(0编辑  收藏  举报