/** 127. Word Ladder * 2016-5-21 by Mingyang * This is a typical topic to convert the topic to graph, first we start with a string start * We first map the topic, vertex is each string, then The last two strings, if one character apart, we make a connection. * Next look at the advantages of this method, notice that our character set has only lowercase letters, and the string length is fixed, * assumed to be L. Then you can notice that each character can correspond to the edge of 25 (26 lowercase letters minus themselves), * then a string may exist edge is 25*l bar. The next step is to detect if the strings of these edges are in the dictionary and get a complete picture structure. * Key 1. Just as we used to do with the queue when we used to do the tree, so that all the child nodes are push into the queue, and each line is accurate to how many of the number of the bank * Good control when to enter the next line. */ Public intLadderlength (string start, String end, set<string>dict) { if(Start = =NULL|| End = =NULL|| Start.length () = = 0 | | End.length () = = 0 | | Start.length ()! =end.length ())return0; LinkedList<String> queue =NewLinkedlist<string>(); Set<String> visited =NewHashset<string>(); intLevel = 1; intLastnum = 1; intCurnum = 0; Queue.offer (start); Visited.add (start); while(!Queue.isempty ()) {String cur=Queue.poll (); Lastnum--; for(inti = 0; I < cur.length (); i++) { Char[] Charcur =Cur.tochararray (); for(Charc = ' a '; C <= ' z '; C++) {Charcur[i]=C; String Temp=NewString (charcur); if(Temp.equals (end))returnLevel + 1; if(Dict.contains (temp) &&!visited.contains (temp)) {Curnum++; Queue.offer (temp); Visited.add (temp); } } } if(Lastnum = = 0) {Lastnum=Curnum; Curnum= 0; level++; } } return0; }
127. Word Ladder