[Leetcode] [JAVA] Word Ladder II

Source: Internet
Author: User

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 ']  ]

Note:

    • All words has the same length.
    • All words contain only lowercase alphabetic characters.

Difficulty is very high of a problem. With the idea of Word Ladder I, the nature of this problem is also the traversal problem of graphs, which is to find all the shortest paths from a given starting point to a given end point.

In Word Ladder I, a legal path is found to return. However, after finding one of these issues, the problem becomes more complicated because the previous nodes in the breadth-first traversal are out of the queue and cannot be retrieved.

So, using the idea in Word Ladder I, not only records the distance from start of each node, but also uses list to record the precursor node on all the shortest paths to this node. As an example:

The list of 6 should be 2 and 3, because 5 is not a point on the shortest path.

The HashMap is used to deal with the mappings between nodes and lists.

In this way, in the process of breadth-first traversal, there are several situations:

1. Adjacent node new node, then the new node into the queue; Create a new node list and add the current node to the list of new nodes; the shortest path length of the record new node is the shortest path length of the current node l+1

2. Adjacent nodes in the queue (for example, the node 3 out of the queue, 6 is still in the queue) and the shortest path length of adjacent nodes = current node Shortest path length +1, then the description is another shortest path, only need to add the current node to the list of adjacent nodes.

3. Adjacent nodes in the queue and the shortest path length of adjacent nodes < The shortest path length of the current node +1, indicating that this is not the shortest path, then do nothing, the current node silently out of the queue.

So we can get a few chains from start to end, and from end we use backtracking to record all the nodes on the chain.

The code is as follows:

1hashmap<string, arraylist<string>> nodeset =NewHashmap<string, arraylist<string>>();2      PublicList<list<string>> findladders (string start, String end, set<string>dict) {3list<list<string>> re =NewArraylist<list<string>>();4queue<string> q =NewLinkedlist<string>();5hashset<string> HS =NewHashset<string>();6hashmap<string, integer> dist =NewHashmap<string, integer>();7 Q.add (start);8Nodeset.put (Start,NewArraylist<string>());9Nodeset.put (End,NewArraylist<string>());TenDist.put (Start, 1); One          A          while(!Q.isempty ()) { -String temp =Q.poll (); -             intL =Dist.get (temp); the Hs.add (temp); -              for(intI=0;i<temp.length (); i++) { -                  for(CharC= ' a '; c<= ' z '; C + +) { -                     if(Temp.charat (i) = =c) +                         Continue; -StringBuilder SB =NewStringBuilder (temp); + Sb.setcharat (i,c); AString next =sb.tostring (); at                     if(Next.equals (end)) { -                         if(!Dist.containskey (end)) { -Dist.put (end,l+1); - nodeset.get (end). Add (temp); -                         } -                         Else if(Dist.get (end) ==l+1) in nodeset.get (end). Add (temp); -                     } to                     Else if(Dict.contains (next) &&!Hs.contains (Next)) { +                         if(!Dist.containskey (Next)) { - Q.add (next); theDist.put (Next, l+1); *arraylist<string> arr =NewArraylist<string>(); $ Arr.add (temp);Panax Notoginseng Nodeset.put (Next, arr); -}Else if(Dist.get (Next) ==l+1) the Nodeset.get (Next). Add (temp); +                     } A                 } the             } +         } -list<string> Path =NewArraylist<string>(); $ Path.add (end); $ Collect (Start,re,path,nodeset.get (end)); -         returnre; -     } the      Public voidCollect (String start, list<list<string>> Re, list<string> path, arraylist<string>prevnodes) -     {Wuyi          for(intI=0;i<prevnodes.size (); i++) the         { -Path.add (0, Prevnodes.get (i)); Wu             if(Prevnodes.get (i). Equals (start)) { -List<string> pathcopy =NewArraylist<string>(path); About Re.add (pathcopy); $             } -             Else - Collect (Start,re,path,nodeset.get (Prevnodes.get (i))); -Path.remove (0); A         } +}

[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.