Well, this problem have a nice BFS structure.
Let's see the example in the problem statement.
start = "hit"
end = "cog"
dict = ["hot", "dot", "dog", "lot", "log"]
Since only one letter can is changed at a time, if we start from "hit"
, we can only change to those words which has only One different letter from it, like "hot"
. Putting in graph-theoretic terms, we can say "hot"
a neighbor of "hit"
.
The idea was simpy to begin from start
, then visit its neighbors and then the non-visited neighbors of its neighbors ... Well, this is just the typical BFS structure.
To simplify the problem, we insert end
into dict
. Once We meet end
during the BFS, we know we have found the answer. We maintain a variable for the current distance of the dist
transformation and update it by after dist++
we finish a round of BFS Search (note that it should fit the definition of the distance in the problem statement). Also, to avoid visiting a word for more than once, we erase it from dict
once it is visited.
The code is as follows. It can still is speed up if we also begin from end
. Once we meet the same word from start
end
and, we know we is done. This link provides a nice two-end search solution.
1 classSolution {2 Public:3 intLadderlength (stringBeginword,stringEndword, unordered_set<string>&worddict) {4 Worddict.insert (Endword);5queue<string>tovisit;6 addnextwords (Beginword, Worddict, tovisit);7 intDist =2;8 while(!Tovisit.empty ()) {9 intnum =tovisit.size ();Ten for(inti =0; i < num; i++) { One stringWord =Tovisit.front (); A Tovisit.pop (); - if(Word = = Endword)returnDist; - addnextwords (Word, worddict, tovisit); the } -dist++; - } - } + Private: - voidAddnextwords (stringWord, unordered_set<string>& Worddict, queue<string>&tovisit) { + worddict.erase (word); A for(intp =0; P < (int) Word.length (); p++) { at CharLetter =Word[p]; - for(intK =0; K < -; k++) { -WORD[P] ='a'+K; - if(Worddict.find (word)! =Worddict.end ()) { - Tovisit.push (word); - worddict.erase (word); in } - } toWORD[P] =Letter ; + } - } the};
[Leetcode] Word Ladder