Skip to content

Commit 5f7c583

Browse files
add 0126
1 parent 4e88bca commit 5f7c583

File tree

2 files changed

+105
-0
lines changed

2 files changed

+105
-0
lines changed

src/0126-Word-Ladder-II/0126.cpp

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
class Solution
2+
{
3+
public:
4+
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)
5+
{
6+
int step = 2;
7+
vector<vector<string>> res;
8+
unordered_set<string> wordDict(wordList.begin(), wordList.end());
9+
if (wordDict.count(endWord) == 0) return res;
10+
unordered_map<string, vector<vector<string>>> s1, s2, stack;
11+
s1[beginWord] = {{beginWord}};
12+
s2[endWord] = {{endWord}};
13+
14+
while (!s1.empty())
15+
{
16+
stack.clear();
17+
for (auto s : s1) wordDict.erase(s.first);
18+
for (auto s : s1)
19+
{
20+
for (int i = 0; i < beginWord.size(); ++i)
21+
{
22+
for (char c = 'a'; c <= 'z'; ++c)
23+
{
24+
string tmp = s.first;
25+
tmp[i] = c;
26+
if (!wordDict.count(tmp)) continue;
27+
if (s2.count(tmp))
28+
{
29+
if (s.second[0][0] == beginWord)
30+
{
31+
for (auto& f : s.second)
32+
{
33+
for (auto& v : s2[tmp])
34+
{
35+
vector<string> tp = f;
36+
tp.insert(tp.end(), v.rbegin(), v.rend());
37+
res.emplace_back(tp);
38+
}
39+
}
40+
}
41+
else
42+
{
43+
for (auto& f : s.second)
44+
{
45+
for (auto& v : s2[tmp])
46+
{
47+
vector<string> tp = v;
48+
tp.insert(tp.end(), f.rbegin(), f.rend());
49+
res.emplace_back(tp);
50+
}
51+
}
52+
}
53+
}
54+
for (auto& p : s.second)
55+
{
56+
vector<string> tp = p;
57+
tp.push_back(tmp);
58+
stack[tmp].emplace_back(tp);
59+
}
60+
}
61+
}
62+
}
63+
s1 = stack.size() < s2.size() ? stack : s2;
64+
s2 = stack.size() < s2.size() ? s2 : stack;
65+
++step;
66+
if (!res.empty() and step > res[0].size()) return res;
67+
}
68+
return res;
69+
}
70+
};

src/0126-Word-Ladder-II/0126.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from collections import defaultdict
2+
class Solution:
3+
def findLadders(self, beginWord, endWord, wordList):
4+
wordDict, res = set(wordList), []
5+
if endWord not in wordDict:
6+
return res
7+
8+
s1, s2, step = defaultdict(list), defaultdict(list), 2
9+
s1[beginWord].append([beginWord])
10+
s2[endWord].append([endWord])
11+
while s1:
12+
stack = defaultdict(list)
13+
wordDict -= s1.keys()
14+
15+
for w, paths in s1.items():
16+
for i in range(len(w)):
17+
for j in string.ascii_lowercase:
18+
tmp = w[:i] + j + w[i+1:]
19+
if tmp not in wordDict:
20+
continue
21+
if tmp in s2:
22+
if paths[0][0] == beginWord:
23+
res += [f + b[::-1] for f in paths for b in s2[tmp]]
24+
else:
25+
res += [b + f[::-1] for f in paths for b in s2[tmp]]
26+
stack[tmp] += [p + [tmp] for p in paths]
27+
28+
if len(stack) < len(s2):
29+
s1 = stack
30+
else:
31+
s1, s2 = s2, stack
32+
step += 1
33+
if res and step > len(res[0]):
34+
return res
35+
return res

0 commit comments

Comments
 (0)