题目描述
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
1.每次转换只能改变一个字母。
2.转换过程中的中间单词必须是字典中的单词。
说明:
1.如果不存在这样的转换序列,返回 0。
2.所有单词具有相同的长度。
3. 所有单词只由小写字母组成。
4.字典中不存在重复的单词。
5. 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出: 5
解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5。
示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出: 0
解释: endWord "cog" 不在字典中,所以无法进行转换。
由于题目中要求的是最短转换序列的长度,因此首先想到的就是广度优先搜索。
根据题意分析要点:
- 从起始词开始,每次变一个字母,经过m次变换,变成结束词,期望m尽量小。
- 我们需要找出邻接关系,比如hit它变一个字母会变成_it、h_t、hi_形式的单词,然后看这个新词是否存在于单词表,如果存在,就找到了一个下一层的转换词。
- 同时,要避免重复访问,比如hot->dot->hot这样变回来,只会徒增转换的长度。
- 因此,要将下一个转换词从单词表中删除(单词表的单词是唯一的)。
可能下一层的单词有多个,都要考察,哪一条转换路径先遇到终点词,它就最短。
依据分析给出解题步骤:
- 由一个结点带出下一层的邻接点,所以用BFS,把单词看作节点。
- 维护一个队列,让起点词入列,step为1,然后出列考察。
- 将它的每个字符变成26字母之一,逐个看是否在单词表,如果在,这个新词为下一层的转变词。
- 将它入列,它的step+1,并从单词表中删去这个词。
- 出列入列…重复,当出列的单词和终点词相同,说明遇到了终点词,返回它的step。
- 当队列为空时,BFS结束,始终没有遇到终点词,没有路径通往终点,返回 0。
具体实现代码如下:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> dict(wordList.begin(),wordList.end());
if(dict.find(endWord) == dict.end()) return 0;
//初始化起始点和终点
unordered_set<string> frontSet,backSet,tmp,visited;
frontSet.insert(beginWord);
backSet.insert(endWord);
int step=1;
while(!frontSet.empty() && !backSet.empty()) {
if(backSet.size() < frontSet.size()) {
tmp = frontSet;
frontSet = backSet;
backSet = tmp;
}
tmp.clear();
for(auto word : frontSet) {
for(int i=0;i<word.size();++i) {
char old = word[i];
//开始变换
for(char c='a' ;c<='z' ;++c ) {
if(old == c) continue;
word[i] = c;
if(backSet.find(word) != backSet.end()) return ++step;
if(visited.find(word) == visited.end() && dict.find(word) != dict.end()) {
tmp.insert(word);
visited.insert(word);
}
}
word[i]=old;
}
}
frontSet = tmp;
++step;
}
return 0;
}
};
AC结果: