您的位置:首页 > 其它

Leetcode 126. Word Ladder II

2016-06-30 11:13 357 查看
还是用广搜做,不过要单独定义一个节点的结构,里面包含路径长度(其实没用到),路径头的字符串,路径经过的字符串。

typedef struct Node
{
int path;
string head;
vector<string>vec;
Node(string s)
{
path = 1;
head = s;
vec.push_back(s);
}
Node(Node *p)
{
path = p->path;
head = p->path;
vec = p->vec;
}
}Node;总体思路:用广度搜索树的方法。
一个父节点的子节点就是:找到在wordList中与节点头字符串head相差一个字符的所有字符串,对于找到的每个字符串,另外建立一个节点,节点head的值为该字符串,vec的值为父节点的vec压入该字符串后形成的值,path加一。

分层的方法:每层压入队列完毕后压入head为“#"的节点,每当出队得到head为”#“的节点,说明上一层已经输入完毕。

每层输入:当出队一个节点后,形成的该节点的子节点,入队。

对列的初始化:压入head为beginWord的节点,当作第一层的节点,然后压入head为”#“的节点代表这一层输入完毕。

收集合法的路径:每当head的值为endWord的时候,将该路径保存起来。

终止:当一层输入完毕的时候,查看是否有保存起来的路径,若有则返回。注:当一整层输入完毕,也代表着上一层出队完毕,在这个过程中检查是否有合法的路径,若有则在这一层有合法的路径,并且是最短的。

class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
vector<vector<string>> ve;
wordList.insert(unordered_set<string>::value_type(endWord));
Node *p1 = new Node(beginWord);
queue<Node *>q1;
q1.push(p1);
Node *p2 = new Node("#");
q1.push(p2);
unordered_set<string>unse;
while (!q1.empty())
{
Node *p3 = q1.front();
q1.pop();
if (p3->head != "#")
{
if (p3->head == endWord)
{
ve.push_back(p3->vec);
}
string s = p3->head;
int l = s.size();
for (int i = 0; i < l; i++)
{
char temp = s[i];
for (int j = 'a'; j <= 'z'; j++)
{
if (temp==j)
continue;
s[i] = j;
if (wordList.find(s) != wordList.end())
{
Node *p4 = new Node(p3);
p4->path++;
p4->head = s;
p4->vec.push_back(s);
q1.push(p4);
unse.insert(unordered_set<string>::value_type(s));
}
}
s[i] = temp;
}
delete p3;
p3 = NULL;
}
else
{
delete p3;
p3 = NULL;
Node *p5 = new Node("#");
q1.push(p5);
if (ve.size() != 0)
return ve;
if (q1.front()->head == "#"&&q1.size() == 1)
return ve;
for (unordered_set<string>::iterator it = unse.begin(); it != unse.end(); it++)
{
wordList.erase(*it);
}
unse.clear();
}
}
}
};

若有不懂的,可以在评论中提出,在第一时间内回答哈。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: