-
Notifications
You must be signed in to change notification settings - Fork 13
/
six-degrees-of-kevin-bacon.cpp
94 lines (72 loc) · 2.55 KB
/
six-degrees-of-kevin-bacon.cpp
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
#include <bits/stdc++.h>
struct Node {
std::set<Node*> neighbours{};
Node() noexcept = default;
};
struct Graph {
std::map<std::string, Node*> nodes{};
~Graph() noexcept {
for ( auto [_, node] : nodes )
if ( nullptr != node )
delete(node);
}
[[maybe_unused]] Node* insert(const std::string& actorName) noexcept {
if ( std::end(nodes) == nodes.find(actorName) )
nodes[actorName] = new Node();
return nodes.at(actorName);
}
void process(std::string inputStr) noexcept {
size_t pos{ inputStr.find_first_of(':') };
if ( std::string::npos != pos )
inputStr = inputStr.substr(pos + 1);
std::istringstream iss(inputStr);
std::string tok;
std::set<Node*> curActors{};
while (std::getline(iss, tok, ','))
curActors.insert(this->insert(tok.substr(1)));
for ( auto& curactor : curActors )
for ( const auto& coactor : curActors )
if ( coactor != curactor )
curactor->neighbours.insert(coactor);
}
Node* getByName(const std::string& actorName) const noexcept {
return (std::end(nodes) == nodes.find(actorName) ) ? nullptr : nodes.at(actorName);
}
};
int main() {
std::string actorName, movieCast;
int n;
Graph graph;
getline(std::cin, actorName);
std::cin >> n; std::cin.ignore();
while( n-- && getline(std::cin, movieCast) )
graph.process(movieCast);
Node* cur { graph.getByName(actorName) };
Node* target { graph.getByName("Kevin Bacon") };
std::deque<Node*> queue { cur };
std::map<Node*, size_t> mem { {cur, 1} };
if ( (nullptr == cur) || (nullptr == target) ) {
std::cerr << "Unable to find requested actors!\n";
return EXIT_FAILURE;
}
if ( cur == target ) {
std::cout << 0 << std::endl;
return EXIT_SUCCESS;
}
while ( !std::empty(queue) ) {
cur = queue.front();
queue.pop_front();
if ( cur->neighbours.count(target) ) {
std::cout << mem[cur] << std::endl;
return EXIT_SUCCESS;
}
for ( const auto& neigh : cur->neighbours ) {
if ( std::end(mem) != mem.find(neigh) )
continue;
mem[neigh] = mem[cur] + 1;
queue.push_back(neigh);
}
}
std::cerr << "Unable to find a path!\n";
return EXIT_FAILURE;
}