class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { unordered_set<string> visited; visited.insert(start); queue<string> que; int curLevel = 1; int curLevelNum = 1; int nextLevelNum = 0; que.push(start); while (!que.empty()) { string cur = que.front(); que.pop(); --curLevelNum; for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); ++it) { string temp = *it; if (canChange(temp, cur) && visited.find(temp) == visited.end()) { que.push(temp); visited.insert(temp); ++nextLevelNum; } } if (canChange(cur, end)) return curLevel + 1; if (curLevelNum == 0) { ++curLevel; curLevelNum = nextLevelNum; nextLevelNum = 0; } } return 0; } bool canChange(string a, string b) { if (a.size() != b.size()) return false; int count = 0; for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { if (count == 1) return false; ++count; } } return count == 0 ? false: true; } };