Given words (start and end), and a dictionary, find the length of shortest transformation sequence F Rom start to end, such that:
- One letter can is changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
Start ="hit"
End ="cog"
dict =["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.
At first glance it is difficult to find a problem, in fact, careful analysis is the graph traversal. Think of the words in both start,end and dict as a knot, and if one word can legitimately be converted to another, then there is a path between the two "nodes". The problem is changed to find the shortest path length from start to end.
If you are using a method that scans all dict words and then determines whether they are legitimate to traverse the node, it will time out (because there are cases with too many words in the dict). So you can only use other traversal ideas.
An efficient way to traverse is to get to the current word length, and then to each bit to try to replace it with another character to Traverse, that is, to get the possible legal string, and then determine whether it is equal to end, or in dict and not in the traversed node, so that the time complexity is O (l) only with the length of the word.
For each node, the HashMap is used to save the start to its path length, and the new node will only need to add a length when entering the site.
It is better to use breadth-first traversal, because we only need to get the shortest path length, and breadth first ensures that the first path to end is the shortest (that is, you can return when you reach end).
The code is as follows:
1 Public intLadderlength (string start, String end, set<string>dict) {2Hashmap<string, integer> HM =NewHashmap<string, integer>();3queue<string> q =NewLinkedlist<string>();4 Q.add (start);5Hm.put (start,1);6 7 while(!q.isempty ())8 {9String temp =Q.poll ();Ten intLen =Hm.get (temp); One for(intI=0;i<temp.length (); i++) { A for(CharC= ' a '; c<= ' z '; C + +) { - if(c==Temp.charat (i)) - Continue; theStringBuilder SB =NewStringBuilder (temp); - Sb.setcharat (i,c); -String next =sb.tostring (); - + if(Next.equals (end)) - returnLen+1; + if(Dict.contains (next) &&!Hm.containskey (Next)) { A Q.add (next); atHm.put (next,len+1); - } - } - } - } - return0; in}
[Leetcode][java] Word Ladder