Word Ladder II
Feb 11
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
class Solution {
public:
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > res;
if(start.size()!=end.size()) return res;
// if(start == end) return ;
unordered_set<string> unique;
unique.insert(start);
queue<string> que;
unordered_map<string, string> path;
que.push(start);
path[start] = "";
int q1=1;
int q2=0;
while(q1>0) {
string s = que.front();
que.pop();
--q1;
string pre = "";
for(int i=0; i<s.size(); i++) {
string temp = s;
for(char c='a'; c<='z'; c++) {
temp[i] = c;
if(dict.find(temp)!=dict.end() && unique.find(temp)==dict.end()) {
if(temp == end) {
if(pre!="") {
unique.erase(pre);
}
pre = temp;
vector<string> elems;
elems.push_back(end);
string item = s;
while(item!="") {
elems.insert(elems.begin(), item);
item = path[item];
}
res.push_back(elems);
} else {
unique.insert(temp);
que.push(temp);
path[temp] = s;
++q2;
}
}
}
}
if(q1==0) {
if(!res.empty()) return res;
q1 = q2;
q2 = 0;
}
}
return res;
}
};
class Solution {
public:
class TreeNode{
public:
string val;
TreeNode * parent;
TreeNode(string str, TreeNode* p=NULL):val(str), parent(p){}
};
bool findnode(string temp, TreeNode* p) {
while(p!=NULL) {
if( temp == p->val) return false;
p = p->parent;
}
return true;
}
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<TreeNode*> clean;
vector<vector<string> > res;
if(start.size()!=end.size()) return res;
// if(start == end) return ;
queue<TreeNode*> que;
TreeNode *head = new TreeNode(start);
clean.push_back(head);
TreeNode *p = head;
que.push(p);
int q1=1;
int q2=0;
while(q1>0) {
TreeNode * p = que.front();
string s = p->val;
que.pop();
--q1;
for(int i=0; i<s.size(); i++) {
string temp = s;
for(char c='a'; c<='z'; c++) {
temp[i] = c;
if(dict.find(temp)!=dict.end() && findnode(temp, p) ) {
if(temp == end) {
vector<string> elems;
elems.push_back(end);
while(p!=NULL) {
elems.insert(elems.begin(), p->val);
p = p->parent;
}
res.push_back(elems);
} else {
TreeNode* tn = new TreeNode(temp,p);
clean.push_back(tn);
que.push(tn);
++q2;
}
}
}
}
if(q1==0) {
if(!res.empty()) return res;
q1 = q2;
q2 = 0;
}
}
for(int i=0; i<clean.size(); i++) {
delete clean[i];
clean[i] = NULL;
}
return res;
}
};