127. Word Ladder(M)

127. Word LadderGiven 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 transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
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.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
  • Difficulty:Medium
  • Total Accepted:129.6K
  • Total Submissions:667.5K
  • Contributor:LeetCode

 1 class Solution {
 2 public:
 3     bool cmpwrd(string str1, string str2)
 4     {
 5         size_t strlen = str1.size();
 6         int cnt = 0;
 7         for (int i = 0; i < strlen; ++i)
 8         {
 9             if(str1[i] == str2[i]) ++cnt;
10         }
11         if(cnt == (strlen - 1)) return true;
12         return false;
13     }
14
15     int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
16         if(find(wordList.begin(), wordList.end(), endWord) == wordList.end()) return 0;
17         size_t wLlen = wordList.size();
18         vector<bool> visited(wLlen, false);
19         int sum = 1;
20         queue<string> qs;
21         qs.push(beginWord);
22         qs.push("#"); // level flag
23
24         while (!qs.empty())
25         {
26             string tmpstr = qs.front();
27             qs.pop();
28             if(tmpstr == "#")
29             {
30                 if(!qs.empty())
31                 {
32                     qs.push(tmpstr);
33                     tmpstr = qs.front();
34                     qs.pop();
35                     ++sum;
36                 }
37                 else return 0;
38             }
39
40             if(tmpstr == endWord) return sum;
41
42             //seek for all the possible next node
43             for (int j = 0; j < wLlen; ++j)
44             {
45                 if(!visited[j] && cmpwrd(tmpstr, wordList[j]))
46                 {
47                     if(tmpstr == endWord)
48                     {
49                         //cout << wordList[j] << "\n" << endWord << endl;
50                         return (++sum);
51                     }
52                     //cout << wordList[j] << " ";
53                     visited[j] = true;
54                     qs.push(wordList[j]);
55                 }
56             }
57             //cout << endl;
58         }
59         return sum;
60     }
61 };

12.21%  Runtime: 806 ms 39 / 39 test cases passed

 1 class Solution {  //by kaishen2
 2 public:
 3     int ladderLength(string beginWord, string endWord, vector<string>& wordDict) {
 4         unordered_set<string> word_dict_;
 5         for (auto &word : wordDict) word_dict_.insert(word);
 6         if (word_dict_.find(endWord) == word_dict_.end()) return 0;
 7         else word_dict_.erase(endWord);
 8         unordered_set<string> q1, q2, temp;
 9         q1.insert(beginWord);
10         q2.insert(endWord);
11         int count = 0;
12         while (!q1.empty() && !q2.empty()) {
13             ++count;
14             if (q1.size() > q2.size()) swap(q1, q2);
15             temp.clear();
16             for (auto word_ : q1) {
17                 for (int j = 0; j < word_.size(); ++j) {
18                     char hold = word_[j];
19                     for (char i = ‘a‘; i <= ‘z‘; ++i) {
20                         word_[j] = i;
21                         if (q2.find(word_) != q2.end())  return count + 1;
22                         if (word_dict_.find(word_) != word_dict_.end()) {
23                             word_dict_.erase(word_);
24                             temp.insert(word_);
25                         }
26                     }
27                     word_[j] = hold;
28                 }
29             }
30             swap(q1, temp);
31         }
32         return 0;
33     }
34 };

93.07% 35ms

时间: 2024-07-31 14:29:02

127. Word Ladder(M)的相关文章

127. Word Ladder(js)

127. 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 transformed word must exi

Leetcode 127. Word Ladder

思路: 1 class Solution(object): 2 def __init__(self): 3 return 4 5 def ladderLength(self, beginWord, endWord, wordList): 6 """ 7 :type beginWord: str 8 :type endWord: str 9 :type wordList: List[str] 10 :rtype: int 11 """ 12 fro

leetcode 127. Word Ladder ----- java

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 li

127. Word Ladder

相当于bfs 1 public int ladderLength(String beginWord, String endWord, Set<String> wordList) { 2 if(beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() != beginWord.length() || wordList == null) { 3 return 0; 4 } 5 Set<

Java for LeetCode 127 Word Ladder

Given two words (beginWord and endWord), and a dictionary, 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 dictionary For exam

(Java) LeetCode 127. 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 transformed word must exist in the word li

LC 127. Word Ladder (two end bfs)

Link class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> words; for(auto &s:wordList){ words.insert(s); } if(words.find(endWord)==words.end()) return 0; unordere

[LeetCode] 126. Word Ladder II_Hard tag: BFS&amp;DFS

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the word list. Note

leetcode Word Ladder II

和上题 Word Ladder I题目差不多,不过这里是要记录所有最段路径的可能. 不同点在于,我们不能再BFS每层的时候把相距一个字符的字符串在dict中删除,因为hot -> hit 的话其他的例如 jit -> hit 就是hit可以出现在两条路径里头.所以不能立马删除.但是我们发现我们可以删除的是我们遍历完的每层的字符串,我们用known来存遍历完的层,unknown来存没有遍历的层,那么每次求得下一层unknown的时候,就首先把known里面有的从dic中删除. 主要思路还是和上一