diff --git a/127-word-ladder/memo.md b/127-word-ladder/memo.md new file mode 100644 index 0000000..9d15bd1 --- /dev/null +++ b/127-word-ladder/memo.md @@ -0,0 +1,11 @@ +### step1 + +BFSでbeginWordから1文字ずつ変えながら探索する方法で実装。 + +### step2 + +qの名前をwordToCountに変更。 + +### step3 + +3回通すまで書き直し。 diff --git a/127-word-ladder/step1.cpp b/127-word-ladder/step1.cpp new file mode 100644 index 0000000..dd926dc --- /dev/null +++ b/127-word-ladder/step1.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set wordSet(wordList.begin(), wordList.end()); + + if (!wordSet.count(endWord)) { + return 0; + } + + queue> q; + q.push({ beginWord, 1 }); + + while (!q.empty()) { + auto [word, steps] = q.front(); + q.pop(); + for (int i = 0; i < word.size(); i++) { + string temp = word; + for (char c = 'a'; c <= 'z'; c++) { + temp[i] = c; + if (temp == endWord) { + return steps + 1; + } + if (wordSet.count(temp)) { + q.push({ temp, steps + 1 }); + wordSet.erase(temp); + } + } + } + } + return 0; + } +}; diff --git a/127-word-ladder/step2.cpp b/127-word-ladder/step2.cpp new file mode 100644 index 0000000..3d33f41 --- /dev/null +++ b/127-word-ladder/step2.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set wordSet(wordList.begin(), wordList.end()); + + if (!wordSet.count(endWord)) { + return 0; + } + + queue> wordToCount; + wordToCount.push({ beginWord, 1 }); + + while (!wordToCount.empty()) { + auto [word, steps] = wordToCount.front(); + wordToCount.pop(); + for (int i = 0; i < word.size(); i++) { + string temp = word; + for (char c = 'a'; c <= 'z'; c++) { + temp[i] = c; + if (temp == endWord) { + return steps + 1; + } + if (wordSet.count(temp)) { + wordToCount.push({ temp, steps + 1 }); + wordSet.erase(temp); + } + } + } + } + return 0; + } +}; diff --git a/127-word-ladder/step3.cpp b/127-word-ladder/step3.cpp new file mode 100644 index 0000000..3d33f41 --- /dev/null +++ b/127-word-ladder/step3.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set wordSet(wordList.begin(), wordList.end()); + + if (!wordSet.count(endWord)) { + return 0; + } + + queue> wordToCount; + wordToCount.push({ beginWord, 1 }); + + while (!wordToCount.empty()) { + auto [word, steps] = wordToCount.front(); + wordToCount.pop(); + for (int i = 0; i < word.size(); i++) { + string temp = word; + for (char c = 'a'; c <= 'z'; c++) { + temp[i] = c; + if (temp == endWord) { + return steps + 1; + } + if (wordSet.count(temp)) { + wordToCount.push({ temp, steps + 1 }); + wordSet.erase(temp); + } + } + } + } + return 0; + } +};