/
WordLadder_2.cpp
95 lines (86 loc) · 2.71 KB
/
WordLadder_2.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
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 {
void buildpath(unordered_map<string, vector<string> >& prevs,
string word, vector<string> &path, vector<vector<string> > &paths)
{
if(prevs[word].empty())
{
path.push_back(word);
vector<string> tpath = path;
reverse(tpath.begin(), tpath.end());
paths.push_back(tpath);
path.pop_back();
return;
}
vector<string> v = prevs[word];
path.push_back(word);
for(int i = 0; i < v.size(); i++)
{
buildpath(prevs, v[i], path, paths);
}
path.pop_back();
}
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string> > paths;
unordered_map<string, vector<string> > prevs;
prevs[start] = vector<string>();
unordered_map<string, int> dists;
dists[start] = 1;
queue<string> q;
q.push(start);
dict.insert(start);
dict.insert(end);
while(!q.empty())
{
string head = q.front();
q.pop();
int dist = dists[head];
for(int i = 0; i < head.length(); i++)
{
for(int j = 0; j < 26; j++)
{
if(j + 'a' == head[i])
continue;
string temp = head;
temp[i] = j + 'a';
if(dict.find(temp) == dict.end())
continue;
if(dists.find(temp) == dists.end())
{
q.push(temp);
dists[temp] = dist + 1;
}
if(dists[temp] > dist)
{
if(prevs.find(temp) == prevs.end())
prevs[temp] = vector<string>();
prevs[temp].push_back(head);
}
}
}
}
if(prevs[end].empty())
return paths;
vector<string> path;
buildpath(prevs, end, path, paths);
return paths;
}
};