|
| 1 | +/* |
| 2 | +Word Ladder |
| 3 | +=========== |
| 4 | +
|
| 5 | +A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words such that: |
| 6 | +
|
| 7 | +The first word in the sequence is beginWord. |
| 8 | +The last word in the sequence is endWord. |
| 9 | +Only one letter is different between each adjacent pair of words in the sequence. |
| 10 | +Every word in the sequence is in wordList. |
| 11 | +Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] |
| 15 | +Output: 5 |
| 16 | +Explanation: One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog" with 5 words. |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] |
| 20 | +Output: 0 |
| 21 | +Explanation: The endWord "cog" is not in wordList, therefore there is no possible transformation. |
| 22 | +
|
| 23 | +Constraints: |
| 24 | +1 <= beginWord.length <= 10 |
| 25 | +endWord.length == beginWord.length |
| 26 | +1 <= wordList.length <= 5000 |
| 27 | +wordList[i].length == beginWord.length |
| 28 | +beginWord, endWord, and wordList[i] consist of lowercase English letters. |
| 29 | +beginWord != endWord |
| 30 | +All the strings in wordList are unique. |
| 31 | +*/ |
| 32 | + |
| 33 | +class Solution |
| 34 | +{ |
| 35 | +public: |
| 36 | + int ladderLength(string beginWord, string endWord, vector<string> &wordList) |
| 37 | + { |
| 38 | + unordered_set<string> left(wordList.begin(), wordList.end()); |
| 39 | + |
| 40 | + if (left.find(endWord) == left.end()) |
| 41 | + return 0; |
| 42 | + int ans = 0; |
| 43 | + |
| 44 | + queue<string> pending; |
| 45 | + pending.push(beginWord); |
| 46 | + |
| 47 | + while (pending.size()) |
| 48 | + { |
| 49 | + int size = pending.size(); |
| 50 | + ans++; |
| 51 | + |
| 52 | + for (int i = 0; i < size; ++i) |
| 53 | + { |
| 54 | + auto curr = pending.front(); |
| 55 | + pending.pop(); |
| 56 | + |
| 57 | + for (int i = 0; i < curr.size(); ++i) |
| 58 | + { |
| 59 | + auto temp = curr; |
| 60 | + for (auto c = 'a'; c <= 'z'; ++c) |
| 61 | + { |
| 62 | + temp[i] = c; |
| 63 | + if (temp == curr) |
| 64 | + continue; |
| 65 | + if (temp == endWord) |
| 66 | + return ans + 1; |
| 67 | + if (left.find(temp) != left.end()) |
| 68 | + { |
| 69 | + left.erase(temp); |
| 70 | + pending.push(temp); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return 0; |
| 78 | + } |
| 79 | +}; |
0 commit comments