Word Ladder
描述:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence 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"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
方法:
BFS
第一个搜索到的结果的层数+2即为结果。
由于都是小写字符,针对每一个字符串的每一位依次从 ‘a'到’z'替换原来的字符,如果替换后的字符串为end串,则结束,如果不是查看字典中是否有,如果有放在队列中。
实现代码一:
该代码没有标记字典中访问过的字符串,导致内存超了。
int ladderLength(string start, string end, set<string> &dict)
{
if(start.size() != end.size()) return 0;
if(start.empty() || end.empty()) return 1;
if(dict.empty()) return 0;
int len = start.length();
if( start.compare(end) == 0) return 2;
queue<string, list<string>> q;
q.push(start);
q.push("#");
int result = 0;
while(!q.empty())
{
string s= q.front();
q.pop();
if( s.compare("#") == 0){
result++;
if( !q.empty())
q.push("#");
continue;
}
for(int i=0; i < len; ++i)
{
char oc = s[i];
for(int j = 0; j < 26; ++j)
{
s[i] = 'a' + j;
if( s[i] == oc)
continue;
if( s.compare(end) == 0)
return result+2;
else if(dict.count(s) > 0)
q.push(s);
}
s[i] = oc;
}
}
return 0;
}
实现二:
加了访问标志。Accept。
代码如下:
int ladderLength1(string start, string end, set<string> &dict)
{
if(start.size() != end.size()) return 0;
if(start.empty() || end.empty()) return 1;
if(dict.empty()) return 0;
int len = start.length();
if( start.compare(end) == 0) return 2;
queue<string> q;
map<string, bool> flag;
q.push(start);
q.push("#");
int result = 0;
while(!q.empty())
{
string s= q.front();
q.pop();
if( s.compare("#") == 0){
result++;
if( !q.empty())
q.push("#");
continue;
}
for(int i=0; i < len; ++i)
{
char oc = s[i];
for(int j = 0; j < 26; ++j)
{
s[i] = 'a' + j;
if( s[i] == oc)
continue;
if( s.compare(end) == 0)
return result+2;
else if(dict.count(s) > 0 && flag.count(s) <= 0)
{
flag[s] = true;
q.push(s);
}
}
s[i] = oc;
}
}
return 0;
}
实现三:
上面代码使用 “#” 来表示一层结束,也就是表示层数。
下面代码使用两个栈交替,每一个栈代表一层的节点情况。
代码如下:
int ladderLength2(string start, string end, set<string> &dict) {
if(start.size() != end.size()) return 0;
if(start.empty() || end.empty()) return 1;
if(dict.empty()) return 0;
queue<string> current,next;
map<string,bool> flag;
int result = 1;
bool found = false;
current.push(start);
while(!current.empty()){
while(!current.empty()){
string origin = current.front();
current.pop();
int len = origin.length();
for(int i=0; i< len; i++){
for(char c='a'; c <= 'z';++c){
swap(c,origin[i]);
if(origin== end){
return result+1;
}
if(dict.count(origin) > 0 && flag.find(origin) == flag.end()){
next.push(origin);
flag[origin] = true;
}
swap(c,origin[i]);
}
}
}
swap(current,next);
result++;
}
return 0;
}