直接看答案。。
1 class Solution { 2 public: 3 int ladderLength(string start, string end, unordered_set<string> &dict) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (start.size() != end.size() || !dict.size()) return 0; 7 int dis = 1; 8 queue<string> queTopush, queTopop; 9 queTopop.push(start); 10 while (dict.size() && !queTopop.empty()) { 11 while (!queTopop.empty()) { 12 string str = queTopop.front(); 13 queTopop.pop(); 14 for (int i = 0; i < str.size(); i++) { 15 for (char j = 'a'; j <= 'z'; j++) { 16 if (j == str[i]) continue; 17 char tmp = str[i]; 18 str[i] = j; 19 if (str == end) return dis+1; 20 if (dict.count(str)) { 21 queTopush.push(str); 22 dict.erase(str); 23 } 24 str[i] = tmp; 25 } 26 } 27 } 28 queTopop.swap(queTopush); 29 dis++; 30 } 31 return 0; 32 } 33 };