目录
题目描述:
字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:
序列中第一个单词是 beginWord 。
序列中最后一个单词是 endWord 。
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典 wordList 中的单词。
给你两个单词 beginWord 和 endWord 和一个字典 wordList ,找到从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0。
方法一(单向BFS):
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> sets;
unordered_map<string, int> maps;
for (string str : wordList)
{
sets.insert(str);
}
queue<string> que;
que.push(beginWord);
maps[beginWord]++;
int ans = 1;
while (!que.empty())
{
int n = que.size();
for (int i = 0; i < n; i++)
{
string cur = que.front();
que.pop();
//枚举替换各个位置
for (int loc = 0; loc < cur.size(); loc++)
{
//枚举替换成其他字母
for (int k = 0; k < 26; k++)
{
char temp = cur[loc];
cur[loc] = 'a' + k;
if (sets.count(cur))
{
if (cur == endWord)
{
return ans + 1;
}
if (!maps.count(cur))
{
maps[cur]++;
que.push(cur);
}
}
cur[loc] = temp;
}
}
}
ans++;
}
return 0;
}
};
经典的单向bfs,依旧是bfs的练习题。
方法二(双向BFS):
class Solution {
public:
unordered_set<string> sets;
int update(queue<string>& curque, unordered_map<string, int>& curmap, unordered_map<string, int>& othermap)
{
int n = curque.size();
for (int i = 0; i < n; i++)
{
string cur = curque.front();
curque.pop();
for (int loc = 0; loc < cur.size(); loc++)
{
for (int j = 0; j < 26; j++)
{
string temp = cur;
cur[loc] = 'a' + j;
//如果是字典中的单词,而且是一个在当前搜索方向未出现过的单词
if (sets.count(cur) && !curmap.count(cur))
{
//如果另外一个搜索方向也有这个单词,说明出现了状态重叠,可以确定找到了这个单词
if (othermap.count(cur))
{
return curmap[temp] + othermap[cur];
}
curque.push(cur);
//找到的新的单词所对应的数字是序列长度,不是简单的curmap[cur]++
curmap[cur] = curmap[temp] + 1;
}
cur = temp;
}
}
}
return -1;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
for (string str : wordList)
{
sets.insert(str);
}
//如果endWord不在字典中,无法转换
if (!sets.count(endWord))
{
return 0;
}
//两个哈希表,分别记录两个方向搜索的状态,每个状态所对应的整数代表当前方向到达这个状态所需要的序列长度
unordered_map<string, int> beginmaps;
unordered_map<string, int> endmaps;
queue<string> beginque;
queue<string> endque;
beginque.push(beginWord);
beginmaps[beginWord]++;
endque.push(endWord);
endmaps[endWord]++;
int ans = 0;
while (!beginque.empty() && !endque.empty())
{
if (beginque.size() <= endque.size())
{
ans = update(beginque, beginmaps, endmaps);
if (ans != -1) return ans;
}
else
{
ans = update(endque, endmaps, beginmaps);
if (ans != -1) return ans;
}
}
return 0;
}
};
双向BFS,速度快了很多
写完解法时,有个错误让我愣了好一会,后来发现下面代码中if里的判断条件应该加个=,因为例如样例【beginWord = "hog" ,endWord = "cog" ,wordList = ["cog"]】,一开始beginque和endque的大小都是1,若if中没有=,则会从目标方向也就是"cog"开始搜索,由于"hog"不在字典中,所以在update()函数中将不会找到任何单词,所以队列endque大小变为0,最终退出主函数中的while循环,返回了0。
if (beginque.size() <= endque.size())
{
ans = update(beginque, beginmaps, endmaps);
if (ans != -1) return ans;
}