-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode 126.cpp
More file actions
69 lines (62 loc) · 1.99 KB
/
Leetcode 126.cpp
File metadata and controls
69 lines (62 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
vector<vector<string>> ans;
string b;
private:
void dfs(string word, vector<string>&seq, unordered_map<string,int>&hash){
if(word == b){
reverse(seq.begin(),seq.end());
ans.push_back(seq);
reverse(seq.begin(),seq.end());
return;
}
int steps = hash[word];
for(int i=0;i<word.size();i++){
char original = word[i];
for(char ch ='a';ch<='z';ch++){
word[i]=ch;
if(hash.find(word)!=hash.end() && steps == 1+hash[word]){
seq.push_back(word);
dfs(word,seq,hash);
seq.pop_back();
}
}
word[i]=original;
}
}
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
//step 1: create a map for storing level paths
queue<string>q;
b=beginWord;
unordered_map<string,int>hash;
unordered_set<string>s(wordList.begin(),wordList.end());
s.erase(beginWord);
q.push(beginWord);
hash[beginWord]=0;
while(!q.empty()){
string word = q.front();
int step = hash[word];
q.pop();
if(word == endWord)break;
for(int i=0;i<word.size();i++){
char original = word[i];
for(char ch ='a';ch<='z';ch++){
word[i]=ch;
if(s.find(word)!=s.end()){
hash[word]=step+1;
s.erase(word);
q.push(word);
}
}
word[i]=original;
}
}
//step 2: backtrack in the map
if(hash.find(endWord)!=hash.end()){
vector<string>seq;
seq.push_back(endWord);
dfs(endWord,seq,hash);
}
return ans;
}
};