首页 > 其他 > 详细

[LeetCode] Word Ladder

时间:2015-06-25 01:18:28      阅读:251      评论:0      收藏:0      [点我收藏+]

Well, this problem has 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 be changed at a time, if we start from "hit", we can only change to those words which have only one different letter from it, like "hot". Putting in graph-theoretic terms, we can say that "hot" is a neighbor of "hit".

The idea is simpy to begin from start, then visit its neighbors, 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 dist for the current distance of the transformation and update it by dist++ after 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 be speed up if we also begin from end. Once we meet the same word from start and end, we know we are done. This link provides a nice two-end search solution.

 1 class Solution {
 2 public:
 3     int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
 4         wordDict.insert(endWord);
 5         queue<string> toVisit;
 6         addNextWords(beginWord, wordDict, toVisit);
 7         int dist = 2;
 8         while (!toVisit.empty()) {
 9             int num = toVisit.size();
10             for (int i = 0; i < num; i++) {
11                 string word = toVisit.front();
12                 toVisit.pop();
13                 if (word == endWord) return dist;
14                 addNextWords(word, wordDict, toVisit);
15             }
16             dist++;
17         }
18     }
19 private:
20     void addNextWords(string word, unordered_set<string>& wordDict, queue<string>& toVisit) {
21         wordDict.erase(word);
22         for (int p = 0; p < (int)word.length(); p++) {
23             char letter = word[p];
24             for (int k = 0; k < 26; k++) {
25                 word[p] = a + k;
26                 if (wordDict.find(word) != wordDict.end()) {
27                     toVisit.push(word);
28                     wordDict.erase(word);
29                 }
30             }
31             word[p] = letter;
32         }
33     }
34 };

 

[LeetCode] Word Ladder

原文:http://www.cnblogs.com/jcliBlogger/p/4599041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!