码迷,mamicode.com
首页 > 其他好文 > 详细

127. Word ladder

时间:2016-10-13 07:48:30      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

把这道题想象成bfs,每次生成下次需要访问的一层,然后交替。

然后可以从两头bfs,像挖隧道一样,两边那边更少就从那边走,直到中间有汇合的点,或者两边都挖不下去了

 

 1     public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
 2         if(beginWord == null || endWord == null || endWord.length() != beginWord.length() || wordList == null || wordList.size() == 0) {
 3             return 0;
 4         }
 5         int len = beginWord.length();
 6         Set<String> beginSet = new HashSet<String>();
 7         Set<String> endSet = new HashSet<String>();
 8         Set<String> visited = new HashSet<String>();
 9         beginSet.add(beginWord);
10         endSet.add(endWord);
11         visited.add(beginWord);
12         int dist = 1;
13         while(!beginSet.isEmpty() && !endSet.isEmpty()) {
14             if(beginSet.size() > endSet.size()) {
15                 Set<String> temp = beginSet;
16                 beginSet = endSet;
17                 endSet = temp;
18             }
19             Set<String> toAdd = new HashSet<String>();
20             for(String each: beginSet) {
21                 char[] chs = each.toCharArray();
22                 for(int i = 0; i < len; i++) {
23                     char ch = chs[i];
24                     for(char c = ‘a‘; c <= ‘z‘; c++) {
25                         chs[i] = c;
26                         String tempWord = new String(chs);
27                         if(endSet.contains(tempWord)) {
28                             return ++dist;
29                         }
30                         if(wordList.contains(tempWord) && !visited.contains(tempWord)) {
31                             toAdd.add(tempWord);
32                             wordList.remove(tempWord);
33                             visited.add(tempWord);
34                         }
35                     }
36                     chs[i] = ch;
37                 }
38             }
39             dist++;
40             beginSet = toAdd;
41         }
42         return 0;
43     }

 

127. Word ladder

标签:

原文地址:http://www.cnblogs.com/warmland/p/5955047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!