-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordLadderII.cpp
More file actions
58 lines (52 loc) · 1.91 KB
/
wordLadderII.cpp
File metadata and controls
58 lines (52 loc) · 1.91 KB
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
// Source: https://leetcode.com/problems/word-ladder-ii/
// Author: Miao Zhang
// Date: 2021-01-20
class Solution {
public:
vector<vector<string>> res;
void dfs(string& beginWord, string& endWord, unordered_map<string, unordered_set<string>>& adj, vector<string>& path) {
if (beginWord == endWord) {
path.push_back(beginWord);
res.push_back(path);
path.pop_back();
return;
}
path.push_back(beginWord);
for (auto w: adj[beginWord]) {
dfs(w, endWord, adj, path);
}
path.pop_back();
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_map<string, unordered_set<string>> adj;
unordered_set<string> wordset(wordList.begin(), wordList.end());
queue<string> q;
q.push(beginWord);
unordered_map<string, int> visited;
visited[beginWord] = 0;
while (!q.empty()) {
string word = q.front();
q.pop();
string newword = word;
for (int i = 0; i < word.size(); i++) {
for (char c = 'a'; c <= 'z'; c++) {
if (newword[i] == c) continue;
newword[i] = c;
if (wordset.count(newword) > 0) {
if (visited.count(newword) == 0) {
visited[newword] = visited[word] + 1;
q.push(newword);
adj[word].insert(newword);
} else if (visited[newword] == visited[word] + 1) {
adj[word].insert(newword);
}
}
}
newword[i] = word[i];
}
}
vector<string> path;
dfs(beginWord, endWord, adj, path);
return res;
}
};