class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> s(wordList.begin(), wordList.end()); if (!s.count(endWord)) return 0; queue<string> q; q.push(beginWord); int lvl = 0; while (!q.empty()) { int sz = q.size(); lvl++; for (int i = 0; i < sz; i++) { string cur = q.front(); q.pop(); if (cur == endWord) { return lvl; } for (int j = 0; j < cur.length(); j++) { char saved = cur[j]; for (char c = 'a'; c <= 'z'; ++c) { cur[j] = c; if (s.count(cur)) { q.push(cur); s.erase(cur); } } cur[j] = saved; } } } return 0; } };