Use BFS breadth search
First BFS find Endword, while storing the number of layers in each word
and then endword as the target, find Startword, build the path.
hashmap<string,integer> path = new hashmap<string,integer> (); BFS generates path void BFs (string start, String end, Hashset<string> dict) {Queue queue = new linkedlist& Lt
String> ();
Queue.add (start);
Path.put (start,0);
String current;
while (!queue.isempty ()) {current = (String) queue.poll ();
if (current==end) {continue;
for (int i=0; i<current.length (); i++) {char[] Strchararr = Current.tochararray ();
for (Char ch= ' a '; ch<= ' z '; ch++) {if (strchararr[i] = = ch) {
Continue
} strchararr[i] = ch;
String Newword = new string (Strchararr); if (newword.equals (end) ==true| |
Dict.contains (Newword)) {//each Word can only appear once in path, that is, each word can only appear in one layer, so it is very clever to solve the problem of the ring. if (Path.get (Newword) ==null) {int depth = (int) path.get (current);
Path.put (newword,depth + 1);//Add the next layer to the map queue.add (Newword); }}}}//Find the start Word back from the target word, record All path void Dfs (string start, String end, Hashset<string> dict, list<string> Patharray,list<list<strin g>> result) {//found, all words that require reverse to be added if (start.equals (end) ==true) {Patharray.add (s)
Tart);
Collections.reverse (Patharray);
Result.add (Patharray);
Return
} if (Path.get (start) ==null) {return;
} patharray.add (start);
int nextdepth = (int) path.get (start)-1;
for (int i=0;i<start.length (); i++) {char[] Strchararr = Start.tochararray (); FoR (Char ch= ' a '; ch<= ' z '; ch++) {if (strchararr[i]==ch) {continue;
} strchararr[i] = ch;
String Newword = new string (Strchararr);
One letter at a time, and the number of layers of the word is also the upper layer of the current word if (Path.get (Newword)!=null&& (Path.get (Newword) ==nextdepth)) {
list<string> Newpatharray = new arraylist<string> (Patharray);
DFS (Newword,end,dict,newpatharray,result); List<list<string>> findladders (string start, String end, H Ashset<string> wordlist) {list<list<string>> result = new arraylist<list<string>>
();
list<string> path = new arraylist<string> (); if (start==null| | end==null| |
Start.length ()!=end.length ()) {return result; } BFS (Start, end, wordlist);
DFS (End,start, wordlist, path, result);
return result; }//beats 81.50% of Java submissions.