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;
}
實現二:
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;
}