-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0126_findLadders.cc
105 lines (98 loc) · 2.19 KB
/
Problem_0126_findLadders.cc
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
#include <list>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution
{
private:
list<string> path;
unordered_set<string> dict;
vector<vector<string>> ans;
unordered_set<string> curLevel;
unordered_set<string> nextLevel;
unordered_map<string, vector<string>> g;
// begin -> end,一层层 bfs 去建图
// 找到 begin 到 end 的路径,则返回 true
bool bfs(string& begin, string& end)
{
bool flag = false;
curLevel.emplace(begin);
while (!curLevel.empty())
{
for (auto& s : curLevel)
{
dict.erase(s);
}
for (auto& s : curLevel)
{
string tmp = s;
// 每个位置,字符 a-z 都试一遍
for (int i = 0; i < tmp.size(); ++i)
{
char old = tmp[i];
for (char ch = 'a'; ch <= 'z'; ++ch)
{
if (ch != old)
{
tmp[i] = ch;
if (dict.count(tmp))
{
if (tmp == end)
{
// 找到 begin 到 end 的路径了
flag = true;
}
// 建反图
g[tmp].emplace_back(s);
nextLevel.emplace(tmp);
}
}
}
tmp[i] = old;
}
}
if (flag)
{
// 找到了路径
return true;
}
else
{
curLevel.swap(nextLevel);
nextLevel.clear();
}
}
return false;
}
// dfs 利用 bfs 形成的反图去生成路径
void dfs(string& word, string& target)
{
path.emplace_front(word);
if (word == target)
{
ans.emplace_back(vector<string>(path.begin(), path.end()));
}
for (auto& next : g[word])
{
dfs(next, target);
}
// 回溯
path.pop_front();
}
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList)
{
dict = unordered_set<string>(wordList.begin(), wordList.end());
if (!dict.count(endWord))
{
return ans;
}
if (bfs(beginWord, endWord))
{
dfs(endWord, beginWord);
}
return ans;
}
};