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
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.
- int ladderLength(string start, string end, unordered_set<string> &dict) {
- if(start == end) return 1;
- //prev counts words of current level, next counts for next level, depth denotes current level.
- //same level means same distance from original word.
- int depth = 1, prev =1, next = 0;
- //queue stores intermediate words
- queue<string> q;
- q.push(start);
- //set stores visited words to avoid redundant work.
- unordered_set<string> visited;
- visited.insert(start);
- while(!q.empty()) {
- string cur = q.front();
- q.pop(); prev--;
- //for each letter in the intermediate word, iterate over 26 options and push it into queue if it's a word,
- //don't forget to update level count next.
- for(int i = 0; i < cur.length(); i++){
- for(int j = 0; j < 26; j++){
- string mid = cur;
- mid[i] = 'a' + j;
- if(dict.find(mid) != dict.end() && visited.find(mid) == visited.end()){
- visited.insert(mid);
- q.push(mid);
- next += 1;
- if(mid == end) return depth + 1;
- }
- }
- }
- if(prev == 0) {prev = next; next = 0; depth++;}
- }
- return 0;
- }
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start == end) return 1;
map<string,int> visited;
queue<string> q;
q.push(start);
visited[start] = 1;
while(!q.empty()) {
string cur = q.front();
q.pop();
for(int i = 0; i < cur.length(); i++){
for(int j = 0; j < 26; j++){
string mid = cur;
mid[i] = 'a' + j;
if(mid == end) return visited[cur] + 1;
if(dict.find(mid) != dict.end() && visited.find(mid) == visited.end()){
visited[mid] = visited[cur] + 1;
q.push(mid);
}
}
}
}
return 0;
}
No comments:
Post a Comment