Skip to content

Commit 89e10e8

Browse files
committed
Time: 8 ms (94.28%), Space: 8.9 MB (85.67%) - LeetHub
1 parent 84c9dee commit 89e10e8

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

word-ladder-ii/word-ladder-ii.cpp

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
class Solution {
2+
public:
3+
vector<vector<string>> globalAns;
4+
unordered_map<string, int> depth;
5+
unordered_map<string, vector<string>> adj;
6+
7+
int minLenPath(string& beginWord, string& endWord, vector<string>& wordList) {
8+
unordered_set<string> dict(wordList.begin(), wordList.end());
9+
10+
if (dict.find(endWord) == dict.end())
11+
return 0;
12+
13+
queue<string> q;
14+
q.push(beginWord);
15+
depth[beginWord] = 0;
16+
17+
while (!q.empty()) {
18+
auto x = q.front();
19+
q.pop();
20+
21+
string currWord = x;
22+
int currDepth = depth[currWord];
23+
24+
if (currWord == endWord)
25+
return currDepth;
26+
27+
// check its children
28+
for (int i = 0; i < (int)currWord.size(); i++) {
29+
char old = currWord[i];
30+
31+
for (int j = 0; j < 26; j++) {
32+
if ((j + 'a') == old) continue;
33+
currWord[i] = (j + 'a');
34+
35+
if(dict.find(currWord) == dict.end()) continue;// only if valid word
36+
37+
if (depth.find(currWord) == depth.end()) {
38+
depth[currWord] = currDepth + 1;
39+
adj[x].push_back(currWord);
40+
q.push(currWord);
41+
} else {
42+
if (depth[currWord] == currDepth + 1) {
43+
adj[x].push_back(currWord);
44+
}
45+
}
46+
}
47+
48+
currWord[i] = old;
49+
}
50+
}
51+
52+
return 0;
53+
}
54+
55+
void dfs(string currWord, string& endWord, int k, vector<string>& path) {
56+
path.push_back(currWord);
57+
58+
if (k == 0) {
59+
if (currWord == endWord) {
60+
globalAns.push_back(path);
61+
}
62+
63+
path.pop_back();
64+
return;
65+
}
66+
67+
for (auto u : adj[currWord])
68+
dfs(u, endWord, k - 1, path);
69+
70+
path.pop_back();
71+
}
72+
73+
vector<vector<string>> findLadders(string beginWord, string endWord,
74+
vector<string>& wordList) {
75+
// 1 - find min length of path k
76+
int k = minLenPath(beginWord, endWord, wordList);
77+
78+
// 2 - traverse all paths of length k and print all paths ending with endWord
79+
if (k == 0)
80+
return {};
81+
82+
cout << k << endl;
83+
vector<string> path;
84+
dfs(beginWord, endWord, k, path);
85+
86+
return globalAns;
87+
}
88+
};

0 commit comments

Comments
 (0)