给定字典中的两个词,长度相等。写一个方法,把一个词转换成另一个词, 但是一次只能改变一个字符。每一步得到的新词都必须能在字典中找到。
编写一个程序,返回一个可能的转换序列。如有多个可能的转换序列,你可以返回任何一个。
示例 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" 不在字典中,所以不存在符合要求的转换序列。
C++
class Solution {
public:
vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> st;
for(auto word:wordList) {
st.insert(word);
}
unordered_set<string> visited;
visited.insert(beginWord);
queue<vector<string>> que;
que.push({beginWord});
while(!que.empty()) {
int m=que.size();
for(int i=0;i<m;i++) {
vector<string> vec=que.front();
que.pop();
string str=vec.back();
if(str==endWord) {
return vec;
}
for(int j=0;j<str.size();j++) {
string ss=str;
for(int k=0;k<26;k++) {
char c=k+'a';
if(c!=str[j]) {
ss[j]=c;
}
if(st.find(ss)!=st.end() && visited.find(ss)==visited.end()) {
visited.insert(ss);
vector<string> v=vec;
v.push_back(ss);
que.push(v);
}
}
}
}
}
return {};
}
};