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 }
本文介绍了一个基于BFS算法的简化版WordLadderII问题解决方案,重点在于计算从一个单词转换到另一个单词所需的最少步骤。通过使用队列和哈希集合,该算法有效地遍历了所有可能的转换路径。

61

被折叠的 条评论
为什么被折叠?



