[Leetcode-java] Word Ladder II

Source: Internet
Author: User

Topic:

Given words (start and end), and a dictionary, find all shortest transformation sequence (s) from start to end, such that:

    1. One letter can is changed at a time
    2. Each intermediate word must exist in the dictionary

For example,

Given:
Start ="hit"
End ="cog"
dict =["hot","dot","dog","lot","log"]

Return

  [    [' Hit ', ' hot ', ' dot ', ' dog ', ' cog '],    [' Hit ', ' hot ', ' lot ', ' log ', ' cog ']  ]

Idea: Establish the adjacency list of dict first, the result of the example is as follows:

Hit: [Hot]
COG: [Dog, log]
Hot: [Hits, Lot, dot]
Lot: [Hot, log, dot]
Dog: [Cog, log, dot]
LOG: [Cog, Lot, dog]
Dot: [Lot, hot, dog]

On the basis of word ladderi, because you want to rebuild the result set, you create a node class yourself, save the previous node of each node, so that when the shortest results are found, then find the node's previous node, join the list.

A few things to note:

(1) Before constructing the adjacency list, you need to join start and end to find the result.

(2) When constructing the neighboring linked list, for each word, be sure to replace the char each time, and then restore it for the next judgment.

(3) Each layer of the queue with a num to record the number of node in this layer, as long as the find one, it proves that this layer is the shortest path, set the flag bit is true, the layer loop after the end of the loop.

(4) in the process of looping, it is necessary to determine whether the node has been judged and create a set to record all the nodes that have been judged.

Code:

 Public classSolution {Private classnode{ PublicNode Pre;  PublicString Val;  Publicnode (node p, String s) {Pre=p; Val=s; }    }     PublicList<list<string>> findladders (string start, String end, set<string>dict)        {Dict.add (start); Dict.add (end); //Note (1)Map<string, set<string>> neighbours =calneighbours (dict); List<List<String>> req =NewArraylist<list<string>>(); LinkedList<Node> queue =NewLinkedlist<node>(); Queue.offer (NewNode (NULL, start));//the first of the start node is nullSet<String> visited =NewHashset<string> ();//Note (4)        BooleanFlag =false;//Note (3)         while(!queue.isempty () | | visited.size () = =dict.size ()) {            intnum =queue.size ();  for(inti = 0; i < num; i++) {Node n=Queue.poll (); if(End.equals (n.val)) {Findpath (n, req); Flag=true;//Note (3)}Else{Set<String> temp =Neighbours.get (N.val); if(temp = =NULL|| Temp.size () = = 0)                        Continue; Else{                         for(String s:temp) {if(!visited.contains (s)) {//Note (4)Queue.offer (NewNode (n, s)); }}}} Visited.add (N.val);//Note (4)            }            if(flag) Break; }        if(!flag)//if flag is false, no solution is shown            return NewArraylist<list<string>>(); returnreq; }        Private voidFindpath (Node N, list<list<string>>req) {        //TODO auto-generated Method Stublist<string> temp =NewArraylist<string>();  while(n! =NULL) {Temp.add (0, N.val); N=N.pre;    } req.add (temp); }     PublicMap<string, set<string>> calneighbours (set<string>dict) {Map<string, set<string>> neighbours =NewHashmap<string, set<string>>();  for(String str:dict) {intLen =str.length (); Char[] chars =Str.tochararray ();  for(inti = 0; i < Len; i++){                CharOld = Chars[i];//Note (2)                 for(Charc = ' a '; C <= ' z '; C++){                    if(c = =Chars[i])Continue; Chars[i]=C; String Newstr=NewString (chars); if(Dict.contains (newstr)) {Set<String> set =neighbours.get (str); if(Set! =NULL) Set.add (NEWSTR); Else{Set<String> Newset =NewHashset<string>();                            Newset.add (NEWSTR);                        Neighbours.put (str, newset); }} Chars[i]= old;//Note (2) Reference variables are used to restore each time you run out}//End fot C}//End for Len}//End for Str        returnneighbours; }}

AC time is about 1120ms, so there is a lot of room for improvement, continue to new ideas.

[Leetcode-java] Word Ladder II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.