diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/word_ladder.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/word_ladder.cpp')
-rw-r--r-- | other/word_ladder.cpp | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/other/word_ladder.cpp b/other/word_ladder.cpp new file mode 100644 index 0000000..dfe6b00 --- /dev/null +++ b/other/word_ladder.cpp @@ -0,0 +1,39 @@ +#include "leetcode.h" + +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector<string> &wordList) { + unordered_set<string> dict(wordList.begin(), wordList.end()); + queue<string> q; + q.push(beginWord); + int ladder = 1; + while (!q.empty()) { + int n = q.size(); // + for (int i = 0; i < n; i++) { + string word = q.front(); + q.pop(); + if (word == endWord) + return ladder; + dict.erase(word); + for (int j = 0; j < word.size(); j++) { + char c = word[j]; + for (int k = 0; k < 26; k++) { + word[j] = 'a' + k; + if (dict.find(word) != dict.end()) + q.push(word); + } + word[j] = c; + } + } + ladder++; + } + return 0; + } +}; + +int main() { + Solution obj; + string beginWord = "hit", endWord = "cog"; + vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; + cout << obj.ladderLength(beginWord, endWord, wordList); +} |