leetcode: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
解题思路:
1、使用图的广度优先搜索策略(BFS);
2、由于要返回所有的最短转换序列,使用unordered_map<string , vector<string>>来存储每个节点的前驱节点;
3、使用递归的形式,将unordered_map<string , vector<string>>中存放的节点顺序信息恢复成转换序列。
代码:
class Solution {
private:
vector> pathes;
void buildPathes(unordered_map> &traces , vector &path , const string end)
{
if(traces[end].size() == 0)
{
path.push_back(end);
vector curPath = path;
reverse(curPath.begin() , curPath.end());
pathes.push_back(curPath);
path.pop_back();
return;
}
vector prevs = traces[end];
path.push_back(end);
for(vector::iterator it = prevs.begin() ; it != prevs.end() ; it++)
{
buildPathes(traces , path , *it);
}
path.pop_back();
}
public:
vector> findLadders(string start, string end, unordered_set &dict) {
pathes.clear();
dict.insert(start);
dict.insert(end);
vector prev;
unordered_map> traces;
for(unordered_set::iterator it = dict.begin() ; it != dict.end() ; it++)
{
traces[*it] = prev;
}
vector> layer(2);
bool cur = true;
bool pre = false;
layer[cur].insert(start);
while(true)
{
cur = !cur;
pre = !pre;
for(unordered_set::iterator it = layer[pre].begin(); it != layer[pre].end() ; it++)
{
dict.erase(*it);
}
layer[cur].clear();
for(unordered_set::iterator it = layer[pre].begin(); it != layer[pre].end() ; it++)
{
for(int i = 0 ; i < (*it).size() ; i++)
{
string word = *it;
int stop = word[i] - 'a';
for(int c = (stop + 1)%26 ; c != stop ; c = (c + 1)%26)
{
word[i] = c + 'a';
if(dict.find(word) != dict.end())
{
traces[word].push_back(*it);
layer[cur].insert(word);
}
}
}
}
if(layer[cur].size() == 0)
return pathes;
if(layer[cur].count(end))
break;
}
vector path;
buildPathes(traces, path, end);
return pathes;
}
};
本文介绍了一道LeetCode题目——寻找两个单词之间的最短转换路径,详细解析了使用广度优先搜索策略求解的方法,并阐述了如何通过递归方式获取所有最短转换序列。
564

被折叠的 条评论
为什么被折叠?



