Problem
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.
Code
class Solution { public: map<string,bool> visited; map<string,int> level_num; bool isConv(const std::string& s1,const std::string& s2) { int diff = 0; int m = s1.size(); int n = s2.size(); if(m != n) return false; for(int i = 0; i < n; ++i){ if(s1[i] != s2[i]) ++diff; if(diff > 1) return false; } if(diff == 0) return false; return true; } bool inDict(string start,unordered_set<string> &dict) { std::unordered_set<std::string>::const_iterator got = dict.find (start); return ( got != dict.end() ); } vector<string> getWords(string start,unordered_set<string> &dict) { int n = start.size(); vector<string> result; for(int i = 0;i < n; ++i){ string temp = start; for(int j = 0;j < 26; ++j){ if(start[i] != 'a' + j){ temp[i] = 'a' + j; if(inDict(temp,dict)){ result.push_back(temp); } } } } return result; } int ladderLength(std::string start, std::string end, std::unordered_set<std::string> &dict) { // Start typing your C/C++ solution below // DO NOT write int main() function if(isConv(start,end)) return 2; visited.clear(); level_num.clear(); level_num[start] = 1; deque<string> Q; visited[start] = true; Q.push_back(start); while(!Q.empty()){ string v = Q.front(); Q.pop_front(); vector<string> words = getWords(v,dict); vector<string>::iterator it = words.begin(); for(; it != words.end(); ++it){ string w = *it; if(visited.find(w) == visited.end()){ visited[w] = true; level_num[w] = level_num[v] + 1; if(isConv(w,end)) return level_num[w] + 1; Q.push_back(w); } } } return 0; } };
No comments:
Post a Comment