原题:
解决方法:
用BFS来实现,用一个queue来保存搜索过的路径。到下一层时,将上一层用过的单词从字典中移除。
代码:
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWord to endWord, such that:
- Only one letter can be changed at a time
- Each transformed word must exist in the word list. Note that beginWord isnot a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- Return an empty list if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
解决方法:
用BFS来实现,用一个queue来保存搜索过的路径。到下一层时,将上一层用过的单词从字典中移除。
代码:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> s(wordList.begin(), wordList.end()), words;
vector<vector<string>> res;
queue<vector<string>> q;
q.push({ beginWord });
int level = 1, minLevel = INT_MAX;
while (!q.empty()) {
vector<string> t = q.front();
q.pop();
if (t.size() > level) {
for (auto w : words)
s.erase(w);
words.clear();
level = t.size();
if (level > minLevel)
break;
}
string word = t.back();
for (int j = 0; j < word.size(); j++) {
for (char ch = 'a'; ch <= 'z'; ++ch) {
string temp = word;
temp[j] = ch;
if (!s.count(temp))
continue;
words.insert(temp);
vector<string> newPath = t;
newPath.push_back(temp);
if (temp == endWord) {
res.push_back(newPath);
minLevel = level;
}
else {
q.push(newPath);
}
}
}
}
return res;
}