-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
59 lines (52 loc) · 1.66 KB
/
Copy pathsolution.cpp
File metadata and controls
59 lines (52 loc) · 1.66 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
59
#include <algorithm>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
std::vector<std::string> wordLadder(const std::string& start, const std::string& end, const std::vector<std::string>& dictionary) {
std::unordered_set<std::string> words(dictionary.begin(), dictionary.end());
if (words.find(end) == words.end()) {
return {};
}
std::queue<std::string> frontier;
frontier.push(start);
std::unordered_map<std::string, std::string> parent;
std::unordered_set<std::string> seen;
seen.insert(start);
while (!frontier.empty()) {
const std::string current = frontier.front();
frontier.pop();
if (current == end) {
break;
}
std::string next = current;
for (std::size_t i = 0; i < next.size(); ++i) {
const char original = next[i];
for (char letter = 'a'; letter <= 'z'; ++letter) {
if (letter == original) {
continue;
}
next[i] = letter;
if (words.find(next) != words.end() && seen.find(next) == seen.end()) {
seen.insert(next);
parent[next] = current;
frontier.push(next);
}
}
next[i] = original;
}
}
if (seen.find(end) == seen.end()) {
return {};
}
std::vector<std::string> path;
for (std::string word = end;; word = parent[word]) {
path.push_back(word);
if (word == start) {
break;
}
}
std::reverse(path.begin(), path.end());
return path;
}