题目地址:
https://leetcode.com/problems/word-ladder/
给定两个单词,分别是起始单词和终止单词,再给定一个单词列表,从某个单词出发走一步,可以达到这个单词中某个字母变成另一个字母的单词。问在这种定义下,起始单词至少走多少步会走到终止单词,并且保证所有单词都属于单词列表(起始单词可以不在,终止单词必须在)。如果不存在这样的路径,就返回 0 0 0。
思路是双向BFS。具体想法和单向BFS是一样的,只不过要同时从起点和终点开始搜索。代码如下:
class Solution {
public:
int ladderLength(string begin, string end, vector<string>& words) {
unordered_set<string> ws(words.begin(), words.end());
if (!ws.count(end)) return 0;
ws.insert(begin);
unordered_set<string> bvis, evis;
bvis.insert(begin);
evis.insert(end);
queue<string> bq, eq;
bq.push(begin);
eq.push(end);
auto one_step = [&](queue<string>& bq, unordered_set<string>& bvis,
unordered_set<string>& evis) {
for (int i = bq.size(); i; i--) {
auto t = bq.front();
bq.pop();
auto s = t;
for (int j = 0; j < t.size(); j++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
if (ch == t[j]) continue;
s[j] = ch;
if (ws.count(s) && !bvis.count(s)) {
if (evis.count(s)) return true;
bvis.insert(s);
bq.push(s);
}
}
s[j] = t[j];
}
}
return false;
};
int res = 0;
while (bq.size() && eq.size()) {
res++;
if (bq.size() <= eq.size()) {
if (one_step(bq, bvis, evis)) return res + 1;
} else if (one_step(eq, evis, bvis))
return res + 1;
}
return 0;
}
};
时空复杂度 O ( l ( N + E ) ) O(l(N+E)) O(l(N+E))。 l l l是单词长度, N N N是单词个数 , , , E E E是图的边数。
本文解析了LeetCode上的单词阶梯问题,通过双向BFS算法寻找最短转换路径,从一个单词转换到另一个单词,每次仅改变一个字符,并确保所有中间单词都在给定的单词列表中。文章详细介绍了算法实现过程及代码示例。
2191

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



