|
| 1 | +#include <iostream> |
| 2 | +#include <string> |
| 3 | +#include <queue> |
| 4 | +#include <map> |
| 5 | +#include <unordered_set> |
| 6 | +#include <cassert> |
| 7 | + |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +class Solution { |
| 11 | +public: |
| 12 | + int ladderLength(string beginWord, string endWord, unordered_set<string> &wordList) { |
| 13 | + queue<string> q; |
| 14 | + map<string, bool> visited; |
| 15 | + q.push(beginWord); |
| 16 | + q.push("LEVEL_END_TAG"); |
| 17 | + visited[beginWord] = true; |
| 18 | + int level = 1; |
| 19 | + while (!q.empty()) { |
| 20 | + string word = q.front(); |
| 21 | + q.pop(); |
| 22 | + if (word != "LEVEL_END_TAG") { |
| 23 | + for (int i = 0; i < word.length(); i++) { |
| 24 | + string new_word = word; |
| 25 | + for (int j = 0; j < 26; j++) { |
| 26 | + new_word[i] = j + 'a'; |
| 27 | + |
| 28 | + if (new_word == endWord) { |
| 29 | + level++; |
| 30 | + return level; |
| 31 | + } |
| 32 | + |
| 33 | + auto it = wordList.find(new_word); |
| 34 | + if (it != wordList.end() && !visited[new_word]) { |
| 35 | + q.push(new_word); |
| 36 | + visited[new_word] = true; |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + else { |
| 42 | + level++; |
| 43 | + if (!q.empty()) { |
| 44 | + q.push("LEVEL_END_TAG"); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return 0; |
| 50 | + } |
| 51 | +}; |
| 52 | + |
| 53 | +int main() { |
| 54 | + unordered_set<string> wordList0 = { "hot", "dot", "dog", "lot", "log" }; |
| 55 | + unordered_set<string> wordList1 = { "hot", "dog" } ; |
| 56 | + |
| 57 | + Solution s; |
| 58 | + assert(s.ladderLength("hit", "cog", wordList0) == 5); |
| 59 | + assert(s.ladderLength("hot", "dog", wordList1) == 0); |
| 60 | + |
| 61 | + printf("all tests passed!\n"); |
| 62 | + |
| 63 | + return 0; |
| 64 | +} |
0 commit comments