Given words (beginword and Endword), and a dictionary ' s word list, find the length of shortest trans Formation sequence from Beginword to Endword, such that:
- One letter can is changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
Beginword ="hit"
Endword ="cog"
wordList =["hot","dot","dog","lot","log"]
As one shortest transformation "hit" -> "hot" -> "dot" -> "dog" -> "cog"
is,
Return its length 5
.
Note:
- Return 0 If there is no such transformation sequence.
- All words has the same length.
- All words contain only lowercase alphabetic characters.
As a result of the 126 questions, so this problem is actually only used BFS can Be.
With a 126 answer.
public classSolution { public intLadderlength (string beginword, string endword, set<string>WordList) { if(beginword = =NULL|| Beginword.length () = = 0 | | Wordlist.size () = = 0 | | Beginword.length ()! =endword.length ())return0; returnBFS (beginword,endword,wordlist); } public intBFS (String beginword,string endword,set<string>WordList) {queue Queue=NewLinkedlist<string>(); Queue.add (beginword); intresult = 1; while( !Queue.isempty ()) {String Str=(String) Queue.poll (); if(str.equals (ENDWORD))Continue; for(inti = 0; I <beginword.length (); i++){ Char[] Word =Str.tochararray (); for(Charch = ' A '; ch<= ' z '; ch++) {word[i]=ch; String Nword=NewString (word); if(wordlist.contains (NWORD)) {if(!Map.containskey (NWORD)) {map.put (nword, (int) Map.get (str) + 1); Queue.add (nword); } } if(nword.equals (ENDWORD))return(int) Map.get (str) + 1; } } } return0; }}
Getting rid of the map will be faster.
public classSolution { public intLadderlength (string beginword, string endword, set<string>WordList) { if(beginword = =NULL|| Beginword.length () = = 0 | | Wordlist.size () = = 0 | | Beginword.length ()! =endword.length ())return0; Queue Queue=NewLinkedlist<string>(); Queue.add (beginword); intresult = 1; while( !Queue.isempty ()) { intLen =queue.size (); for(inti = 0;i<len;i++) {String str=(String) Queue.poll (); for(intII = 0; II < str.length (); ii++){ Char[] Word =Str.tochararray (); for(Charch = ' A '; Ch<= ' Z '; ch++) {word[ii]=ch; String Newword=NewString (word); if(wordlist.contains (NEWWORD)) {wordlist.remove (newword); Queue.add (newword); } if(newword.equals (ENDWORD))returnResult+1; } }} Result++; } return0; }}
There is also a faster approach, usually set up in front of the queue to do, will be much faster.
Leetcode 127. Word Ladder-----java