[C + +] leetcode:130 Word Ladder (BFS)

Source: Internet
Author: User

Title:

Given words (start and end), and a dictionary, find the length of shortest transformation sequence F Rom 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 "]

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.
idea: You can think of this problem as a graph. We map the topic to the graph, the vertices are each string, and then the two strings are connected if one character is different. Our character set has only lowercase letters, and the length of the string is fixed, assuming L. Then you can notice that each character can have 25 sides (26 lowercase letters to remove itself), then a string may exist side is 25*l bar. The next step is to check that the corresponding strings are in the dictionary and get a complete picture of the structure. According to the requirements of the topic, equivalent to the shortest path of one vertex to another in this graph, we usually use breadth first. This problem, we can only use the simplest way to do, each change the word of a letter, and then gradually search, the shortest path, the minimum depth of the tree with BFS most suitable. Take a look at the time
    • The word adjacent to the current word, which is another vertex that is the same as the vertex, is a word that changes a letter to the current word and exists within the dictionary.
    • Find the next word of a word, join the BFS queue, we want to remove from the dictionary, because do not delete will cause similar hog->hot->hog such a dead loop. And the deletion of the shortest path has no effect, because we first found the word is definitely the shortest path, we are the sequence traversal to search, the first to find must be the shortest path, even if the other words can be converted to it, the path will certainly not be shorter than the current path. This problem only requires the shortest path length, no need to require the shortest path to output, so you can delete the word.
    • BFS queue with empty string "" to mark the interval between layers and layers, each hit the end of the layer, traverse depth +1, into the next layer.
Attention: 1. Depending on the topic, the path length contains the opening and closing. So just start initializing path to 1.
int path = 1;
2. We use the empty string "" as the delimiter for layers and layers, unlike the nodes of the tree, we use NULL. Here the string and null cannot be compared. if (str! = NULL) Line 16:no match for ' operator!= ' (operand types is ' std::string {aka Std::basic_string<char>} ' and ' long int ')
3. When changing every letter of a word, we need to save the character first and then search for a match. The final search is complete and the site needs to be restored.
char tmp = str[i];
Str[i] = tmp;  Reset back to the original word
4. Set Delete element
(1)
Iterator  Erase (const_iterator position);
(2)
size_type Erase (const value_type& val); 
(3)
Iterator  Erase (const_iterator first, const_iterator last);
5. If the current string gets end after changing a letter, the conversion ends. Returns PATH+1. End and start do not need to be inside the dictionary. This is the termination condition of the BFS search.
if (str = = end) return path + 1; If the changed word equals end returns path+1
Complexity: The worst case scenario is to look at all strings of length l, or the strings in the dictionary. A string of length L has a total of 26^l. Time complexity O (26^l), space requires storage access, O (size (dict)). AC Code:
Class Solution {Public:int ladderlength (string start, String end, unordered_set<string> &dict) {if (s Tart.size () = = 0 | |                End.size () = = 0) return 0;        Queue<string> WORDQ;        Wordq.push (start);        Wordq.push ("");                int path = 1;            while (!wordq.empty ()) {string str = Wordq.front ();                        Wordq.pop ();                if (str! = "") {int len = str.size ();                                        for (int i = 0; i < len; i++) {char tmp = str[i];                        for (char c = ' a '; c <= ' z '; C + +) {if (c = = tmp) continue;                        Str[i] = c; if (str = = end) return path + 1;                            If the changed word equals end returns path+1 if (Dict.find (str)! = Dict.end ()) {                            Wordq.push (str); Dict.erase (STR);  Delete this word in the dictionary to prevent repeated walk}} Str[i] = tmp; Reset back to the original word}} else if (!wordq.empty ()) {//arrives at the end of the current layer and is not the last                The end of the layer path++;            Wordq.push ("");    }} return 0; }};

The essence of this problem is the framework of breadth-first search, but to judge the side of the time need to change characters and look up the operation of the dictionary, which is the basis of the graph search algorithm. Clone Graph.






[C + +] leetcode:130 Word Ladder (BFS)

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.