1. 题目
给定字典中的两个词,长度相等。
写一个方法,把一个词转换成另一个词, 但是一次只能改变一个字符。
每一步得到的新词都必须能在字典中找到。
编写一个程序,返回一个可能的转换序列。如有多个可能的转换序列,你可以返回任何一个。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出:
["hit","hot","dot","lot","log","cog"]
示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出: []
解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-transformer-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
类似题目:
LeetCode 126. 单词接龙 II(图的BFS)
LeetCode 127. 单词接龙(图的BFS/双向BFS)
- 广度优先搜索
class Solution {
public:
vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList) {
vector<string> ans, frontPath, newpath;
int len = wordList.size(), i, k, n, lv = 0;
unordered_map<string,int> m;
vector<bool> visited(len,false);
for(i = 0; i < len; ++i)
{
m[wordList[i]] = i;
if(wordList[i] == beginWord)
visited[i] = true;
}
if(m.find(endWord) == m.end())
return {};
queue<vector<string>> q;
frontPath.push_back(beginWord);
q.push(frontPath);
string str;
while(!q.empty())
{
lv++;
n = q.size();
while(n--)
{
frontPath = q.front();
q.pop();
for(i = 0; i < beginWord.size(); ++i)
{//对每个单词的每个字符进行改变
str = frontPath.back();
for(k = 1; k <= 25; ++k)
{
str[i] += 1;
if(str[i] > 'z')
str[i] = 'a';
if(m.find(str) != m.end() && !visited[m[str]])
{ //在集合中,且没有访问的
newpath = frontPath;
newpath.push_back(str);
q.push(newpath);
visited[m[str]] = true;
if(str == endWord)
return newpath;
}
}
}
}
}
return {};
}
};
308 ms 19.4 MB