[Leetcode] [Java] Word Ladder

Source: Internet
Author: User

Title:

Given words (beginword and Endword), and a dictionary, find the length of shortest transformation se Quence from Beginword to Endword, 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"]

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.
Test Instructions:

Given two words (start Word and end word) and a dictionary. Find the length of the conversion sequence from the beginning word to the end word.

Attention:

1. Only one letter can be changed at a time.

2. Each medium word must be in the dictionary.

For example:

Given:

start  =  " hit "
end  =  " cog "
dict  =  [" hot "," dot "," dog "," Lot "," log "]

One of the shortest conversions to "hit" -> "hot" -> "dot" -> "dog" -> "cog" ,

The returned length is 5.

Attention:

1. If the conversion sequence does not exist, return 0.

2. All words have equal lengths.

3. All the words are lowercase.

Algorithm Analysis:

The problem is to apply BFS and also use BFS to find the shortest path characteristics to solve problems.


Use each word as a node for BFS. When the current string is taken, each of his characters is replaced from the a~z, if in the dictionary, the queue, and the lower count++, and in order to avoid the loop, you need to put the word detected in the dictionary from the dictionary deleted. This allows the words in the queue to be traversed as the next layer, after installing a~z substitution for each character of the current string.

Because BFS is able to traverse all the possibilities of a layer, it is guaranteed that once a word equals (end) is found, the path to return must be the shortest.

---similar to the sequence traversal of a binary tree, the number of layers of the first traversed leaf is the minimum height of the tree, and the first match found in the BFS traversal in the problem is the shortest conversion.
Step by step, the first traversal to the end of the node, of course, the shortest path

AC Code:

<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution {public int ladderlength (string start, String end, Set<string> dict) {if (s Tart==null | | End==null | | Start.length () ==0 | | End.length () ==0 | |                 Start.length ()!=end.length ()) return 0;        linkedlist<string> wordqueue = new linkedlist<string> (); int level = 1;                Defines the current level int curnum = 1;//defines the number of nodes in the current layer int nextnum = 0;//defines the number of nodes in the next layer Wordqueue.add (start);            while (!wordqueue.isempty ()) {String word = wordqueue.poll ();                        curnum--;                for (int i = 0; i < word.length (); i++) {char[] Wordunit = Word.tochararray ();                    for (char j = ' a '; J <= ' Z ', J + +) {Wordunit[i] = j;                                          String temp = new string (wordunit);            if (temp.equals (end))            return level+1;                        if (Dict.contains (temp)) {Wordqueue.add (temp);                        nextnum++;                    Dict.remove (temp); }}} if (Curnum = = 0)//Indicates the end of the layer access, need to go to the next layer {Curnu                m = nextnum;                Nextnum = 0;            level++;    }} return 0; }}</span>

Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Word Ladder

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.