LeetCode127-Word (ladder)

Source: Internet
Author: User
LeetCode127-Word ladder

Given two words (beginword and endword), and a dictionary's word list, find the length of shortest transformation sequence from beginword to endword, such that:

Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,

Given:
Beginword = "hit"
Endword = "cog"
Wordlist = ["hot", "dot", "dog", "lot", "log"]
As one shortest transformation is "hit"-> "hot"-> "dot"-> "dog"-> "cog ",
Return its length 5.

Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.

Analysis 1

To turn this question into a graph theory problem, we will build a graph using the following ideas:

1. The words in beginword, endword, and wordlist are used as nodes in the graph.
2. To determine whether these nodes are reachable: If one character can be converted to another word, it means that the nodes are reachable.
3. Search the graph for the breadth first to find the length from the start point to the end point.

Problem

This was my first thought and implementation, but I encountered a problem: when there are too many words in wordlist, the scale of the graph will become very large,Time-out (limit exceeded)The timeout code is also posted here:

Class solution {PRIVATE: bool isconnect (const string & A, const string & B) {// judge whether two words are reachable; int COUNT = 0; For (INT I = 0; I <. size (); I ++) {if (a [I]! = B [I]) Count ++; If (count> 1) return false;} If (COUNT = 1) // return true with only one character; else return false;} void buildmap (vector <int> & wordmap, Map <string, int> wordtable) {int mapsize = wordtable. size (); For (Auto it1 = wordtable. begin (); it1! = Wordtable. End (); it1 ++) {for (Auto it2 = it1; it2! = Wordtable. end (); it2 ++) {If (isconnect (it1-> first, it2-> first) {// initialize the adjacent matrix (1-up to 0-Not up) wordmap [it1-> second] [it2-> second] = 1; wordmap [it2-> second] [it1-> second] = 1 ;}}}} int BFS (vector <int> & wordmap, string start, string end, Map <string, int> wordtable) {vector <bool> visit (wordtable. size (), false); // Access Table queue <int> q; queue <int> D; // record the auxiliary queue Q from distance. push (wordtable [start]); D. push (1); V Isit [wordtable [start] = true; while (! Q. empty () {int T = D. front (); int I = Q. front (); D. pop (); q. pop (); if (I = wordtable [end]) // find the end {return t;} For (Int J = 0; j <wordmap. size (); j ++) {If (! Visit [J] & wordmap [I] [J] = 1) {visit [J] = true; q. push (j); D. push (t + 1) ;}}// end while return 0;} public: int ladderlength (string beginword, string endword, unordered_set <string> & wordlist) {Map <string, int> wordtable; // word index table wordtable [beginword] = 0; wordtable [endword] = 1; Auto it = wordlist. begin (); int Index = 2; for (; it! = Wordlist. end (); It ++) // {If (wordtable. find (* It) = wordtable. end () wordtable [* It] = index ++; // create a word-index table for easy graph creation} int size = wordtable. size (); vector <int> wordmap (size, vector <int> (size, 0); // initialize the adjacent matrix buildmap (wordmap, wordtable ); // create a map return BFS (wordmap, beginword, endword, wordtable); // return 0 ;}};
Analysis 2

In fact, you do not need to create the entire graph. You can take a step by step, that is:

When you access node A, you can first find all nodes that are connected to node A but not accessed to join the team, and then follow the BFS idea.

However, the modified Code still times out. Later I found that I was"Determine whether two nodes are connected"The algorithm used in this step is too inefficient. Compared with the online idea:

My method is: Compare all the words in the current node with those in wordlist. If the number of different characters is 1, return true; otherwise, return false. The disadvantage of doing so is,Traverse the entire wordlist in any way, and the time complexity of searching is O (N) .

The idea on the net is to replace the current character of the word on the current node (from A ~ Z), and then check whether the replaced words are in the word list. What I don't understand here is that we use unordered_set to save the word list,In the worst case, the time complexity will reach O (N) But generally, it can be in constant time. O (1) Therefore, the time complexity of using unordered_set: Find is lower than the linear time complexity.In this way, the efficiency is improved.

Code
Class solution {PRIVATE: void buildmap (string end, vector <string> & connect, unordered_set <string> & visit, string & Current, const unordered_set <string> & wordlist) {connect. clear (); string cur = current;/* Timeout: time complexity O (n) for (Auto I = wordlist. begin (); I! = Wordlist. End (); I ++) {If (visit. Find (* I )! = Visit. end () continue; If (isconnect (cur, * I) connect. push_back (* I);} */# If 1 for (INT I = 0; I <cur. size (); I ++) {char T = cur [I]; for (char c = 'a'; C <'Z'; C ++) {If (C = T) {continue;} cur [I] = C; If (cur = end | wordlist. find (cur )! = Wordlist. end () & (visit. find (cur) = visit. end () {connect. push_back (cur) ;}} cur [I] = T ;}# endif} int BFS (string beginword, string endword, unordered_set <string> & wordlist) {queue <string> q; queue <int> D; // The auxiliary queue unordered_set <string> visit; vector <string> connect; q. push (beginword); D. push (1); While (! Q. empty () {string current = Q. front (); int tmpdist = D. front (); q. pop (); D. pop (); buildmap (endword, connect, visit, current, wordlist); // obtain the adjacent word if (current = endword) // locate the endpoint {return tmpdist ;} for (INT I = 0; I <connect. size (); I ++) {If (visit. find (connect [I]) = visit. end () // not accessed {visit. insert (connect [I]); q. push (connect [I]); D. push (tmpdist + 1) ;}} return 0; // No path found} public: int ladderlength (string beginword, string endword, unordered_set <string> & wordlist) {int res = BFS (beginword, endword, wordlist); Return res ;}};
Reference

Unordered_set: Find time complexity
Http://www.cplusplus.com/reference/unordered_set/unordered_set/find/

Complexity
Average case: constant.
Worst case: Linear in container size.

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