Leetcode#127 Word Ladder

时间:2021-10-22 22:40:27

原题地址

BFS

Word Ladder II的简化版(参见这篇文章

由于只需要计算步数,所以简单许多。

代码:

 int ladderLength(string start, string end, unordered_set<string> &dict) {
if (start == end)
return ; unordered_set<string> old;
queue<string> layer;
int len = ; layer.push(start);
while (!layer.empty()) {
queue<string> nextLayer;
while (!layer.empty()) {
string str = layer.front();
layer.pop();
if (str == end)
return len;
for (int i = ; i < str.length(); i++) {
for (char j = 'a'; j <= 'z'; j++) {
string next = str;
next[i] = j;
if (old.find(next) == old.end() && dict.find(next) != dict.end()) {
old.insert(next);
nextLayer.push(next);
}
}
}
}
len++;
layer = nextLayer;
} return ;
}