还是参考爱做饭同学
http://www.cnblogs.com/springfor/p/3893499.html
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
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
.
摘抄“
题解:
这道题是套用BFS同时也利用BFS能寻找最短路径的特性来解决问题。
把每个单词作为一个node进行BFS。当取得当前字符串时,对他的每一位字符进行从a~z的替换,如果在字典里面,就入队,并将下层count++,并且为了避免环路,需把在字典里检测到的单词从字典里删除。这样对于当前字符串的每一位字符安装a~z替换后,在queue中的单词就作为下一层需要遍历的单词了。
正因为BFS能够把一层所有可能性都遍历了,所以就保证了一旦找到一个单词equals(end),那么return的路径肯定是最短的。
像给的例子 start = hit,end = cog,dict = [hot, dot, dog, lot, log]
按照上述解题思路的走法就是:
level = 1 hit dict = [hot, dot, dog, lot, log]
ait bit cit ... xit yit zit , hat hbt hct ... hot ... hxt hyt hzt , hia hib hic ... hix hiy hiz
level = 2 hot dict = [dot, dog, lot, log]
aot bot cot dot ... lot ... xot yot zot,hat hbt hct ... hxt hyt hzt,hoa hob hoc ... hox hoy hoz
level = 3 dot lot dict = [dog log]
aot bot ... yot zot,dat dbt ...dyt dzt,doa dob ... dog .. doy doz,
aot bot ... yot zot,lat lbt ... lyt lzt,loa lob ... log... loy loz
level = 4 dog log dict = []
aog bog cog
level = 5 cog dict = []
”
所以这里按照bfs大法, queue就是wordladder, curnum是里面的ladders, nexnum应该是dict里要试的单词。比如hXt,测出来和dict的hat,hot,hit符合,那么nextnum就应该是3.。。此外这里应该思考,如何符合题目中的“shortest transformation”??
bfs 大法应该看binary tree level那题做基础
bfs大法(binary tree level那题)好,重要的话,随着题目重复率,至少可以说十遍。
code里面的两个注释错误比较值得注意
public class Solution { public int ladderLength(String beginWord, String endWord, Set<String> wordDict) { if(wordDict ==null ||wordDict.size()==0|| beginWord==null||endWord==null||beginWord=="" || endWord =="" ) return 0;//Integer.MAX_VALUE?? if(beginWord.equals(endWord)) return 0; LinkedList<String> q = new LinkedList<String>(); q.add(beginWord); int step = 1, curNum=1, nextNum=0; while(!q.isEmpty()){ curNum--; String word = q.poll(); // char[] tst = word.toCharArray(); 不能放在这里,会被同步update for(int i=0; i<word.length();i++){ char[] tst = word.toCharArray(); for(char j='a';j<='z';j++){ tst[i]=j; String tmp = new String(tst); if(tmp.equals(endWord)){ return step+1; // 这里不能写++,必须是+1 } if(wordDict.contains(tmp)){ q.add(tmp); nextNum++; wordDict.remove(tmp); } } } if(curNum==0){ step++; curNum = nextNum; nextNum=0; } } return 0; } }