标签:breadth-first search graph leetcode
题目:Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
int path = 1;2. 我们使用空串“”来作为层与层的分隔符,不同于树的结点,我们用NULL。这里字符串和NULL无法进行比较。
char tmp = str[i];
str[i] = tmp; //重置回原来的单词4. set 删除元素
| (1) |
iterator erase (const_iterator position); |
|---|
| (2) |
size_type erase (const value_type& val); |
|---|
| (3) |
iterator erase (const_iterator first, const_iterator last); |
|---|
if(str == end) return path + 1; //如果改变后的单词等于end 返回path+1复杂度:最坏情况就是把所有长度为L的字符串都看一遍,或者字典内的字符串都看一遍。长度为L的字符串总共有26^L.时间复杂度O(26^L),空间上需要存储访问情况,O(size(dict)).
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start.size() == 0 || end.size() == 0) return 0;
queue<string> wordQ;
wordQ.push(start);
wordQ.push("");
int path = 1;
while(!wordQ.empty())
{
string str = wordQ.front();
wordQ.pop();
if(str != "")
{
int len = str.size();
for(int i = 0; i < len; i++)
{
char tmp = str[i];
for(char c = 'a'; c <= 'z'; c++)
{
if(c == tmp) continue;
str[i] = c;
if(str == end) return path + 1; //如果改变后的单词等于end 返回path+1
if(dict.find(str) != dict.end())
{
wordQ.push(str);
dict.erase(str); //字典内删除这个词 防止反复走
}
}
str[i] = tmp; //重置回原来的单词
}
}
else if(!wordQ.empty())
{
//到达当前层的结尾,并且不是最后一层的结尾
path++;
wordQ.push("");
}
}
return 0;
}
};[C++]LeetCode: 130 Word Ladder (BFS)
标签:breadth-first search graph leetcode
原文地址:http://blog.csdn.net/cinderella_niu/article/details/43239659