标签:
把这道题想象成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 }
标签:
原文地址:http://www.cnblogs.com/warmland/p/5955047.html