标签:
BFS
Word Ladder II的简化版(参见这篇文章)
由于只需要计算步数,所以简单许多。
代码:
1 int ladderLength(string start, string end, unordered_set<string> &dict) { 2 if (start == end) 3 return 0; 4 5 unordered_set<string> old; 6 queue<string> layer; 7 int len = 1; 8 9 layer.push(start); 10 while (!layer.empty()) { 11 queue<string> nextLayer; 12 while (!layer.empty()) { 13 string str = layer.front(); 14 layer.pop(); 15 if (str == end) 16 return len; 17 for (int i = 0; i < str.length(); i++) { 18 for (char j = ‘a‘; j <= ‘z‘; j++) { 19 string next = str; 20 next[i] = j; 21 if (old.find(next) == old.end() && dict.find(next) != dict.end()) { 22 old.insert(next); 23 nextLayer.push(next); 24 } 25 } 26 } 27 } 28 len++; 29 layer = nextLayer; 30 } 31 32 return 0; 33 }
标签:
原文地址:http://www.cnblogs.com/boring09/p/4262998.html