/
word-ladder-ii.cpp
141 lines (115 loc) · 3.15 KB
/
word-ladder-ii.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <iostream>
#include <queue>
using namespace std;
typedef enum {
Clean = 0,
Pending,
Completed,
} Status;
class Solution
{
unordered_map<string, Status> nodes;
unordered_map<string, int> pathLen;
unordered_map<string, vector<string> > trace;
queue<string> sq;
void travel(const string &src, const string &dst)
{
vector<string> backTrace;
if (nodes[dst] == Pending && pathLen[dst] > pathLen[src]) {
backTrace = trace[dst];
backTrace.push_back(src);
trace[dst] = backTrace;
}
if (nodes[dst] == Clean) {
sq.push(dst);
backTrace.push_back(src);
nodes[dst] = Pending;
pathLen[dst] = pathLen[src] + 1;
trace[dst] = backTrace;
}
}
vector<vector<string> >pathTo(const string &dst)
{
vector<vector<string> >pathes;
if (trace[dst].size() > 0) {
for (string src : trace[dst]) {
vector<vector<string> >subPathes = pathTo(src);
for (vector<string> path : subPathes) {
path.push_back(dst);
pathes.push_back(path);
}
}
} else {
vector<string> path;
path.push_back(dst);
pathes.push_back(path);
}
return pathes;
}
public:
vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict)
{
if (start == end) {
vector<string> path;
vector<vector<string> > pathes;
path.push_back(start);
path.push_back(end);
pathes.push_back(path);
return pathes;
}
dict.insert(end);
vector<string> emptyTrace;
sq.push(start);
nodes[start] = Pending;
pathLen[start] = 1;
trace[start] = emptyTrace;
while (!sq.empty()) {
string temp = sq.front();
sq.pop();
if (temp == end) {
return pathTo(end);
}
for (int i = 0; i < temp.length(); ++i) {
string copy = temp;
for (char c = 'a'; c <= 'z'; ++c) {
if (c == temp[i]) continue;
copy[i] = c;
if (dict.count(copy) > 0) {
travel(temp, copy);
}
}
}
}
vector<vector<string> > pathes;
return pathes;
}
};
int main(int argc, char *argv[])
{
Solution solve;
string start("hit");
string end("cog");
unordered_set<string> dict;
string word;
word = "hot";
dict.insert(word);
word = "dot";
dict.insert(word);
word = "dog";
dict.insert(word);
word = "lot";
dict.insert(word);
word = "log";
dict.insert(word);
vector<vector<string> > ans = solve.findLadders(start, end, dict);
for (vector<string> path : ans) {
for (string node : path) {
cout << node << ' ';
}
cout << endl;
}
return 0;
}