LintCode-单词接龙II
给出两个单词(start和end)和一个字典,找出所有从start到end的最短转换序列
比如: 每次只能改变一个字母。 变换过程中的中间单词必须在字典中出现。
注意事项
所有单词具有相同的长度。
所有单词都只包含小写字母。
样例
给出数据如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
返回
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
先直接写了个图+BFS
遍历每两个单词算different,等于1的放进邻接矩阵里面。
然后用没做优化的BFS找end
class Solution {
public:
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return a list of lists of string
*/
struct Destination {
int num = 0;
vector<string> str;
};
struct Path {
string str;
vector<string> path;
};
map<string,bool> isPassed;
void BFS(queue<Path> &order, vector<vector<string>> &result, map<string, Destination> m, const string end) {
int num = order.size();
for (int i = 0; i < num;i++) {
Path s = order.front();
isPassed[s.str]=true;
order.pop();
if (s.str == end) {
result.push_back(s.path);
}
if (m[s.str].num != 0) {
for (auto i : m[s.str].str) {
if(!isPassed[i])
{
Path p;
p.str = i;
p.path = s.path;
p.path.push_back(i);
order.push(p);
}
}
}
}
if (!order.empty() && result.empty())
BFS(order, result, m, end);
return;
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
// write your code here
dict.insert(start);
dict.insert(end);
map<string, Destination> m;
for (