#include "leetcode.h" class Solution { public: int ladderLength(string beginWord, string endWord, vector &wordList) { unordered_set dict(wordList.begin(), wordList.end()); queue 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 wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; cout << obj.ladderLength(beginWord, endWord, wordList); }