-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem85.cpp
More file actions
64 lines (55 loc) · 1.11 KB
/
problem85.cpp
File metadata and controls
64 lines (55 loc) · 1.11 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
60
61
62
63
64
#include <bits/stdc++.h>
using namespace std;
class MagicalKingdom {
int n; // number of castles
vector<vector<int>> adj; // adjacency list
public:
void readInput() {
cin >> n;
adj.resize(n);
cin.ignore(); // clear newline after n
for (int i = 0; i < n; ++i) {
string line;
getline(cin, line);
istringstream iss(line);
int v;
while (iss >> v) {
adj[i].push_back(v);
}
}
}
vector<int> bfsExplore() {
vector<int> order;
vector<bool> visited(n, false);
queue<int> q;
q.push(0);
visited[0] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
order.push_back(u);
for (int v : adj[u]) {
if (!visited[v]) {
visited[v] = true;
q.push(v);
}
}
}
return order;
}
void display() {
vector<int> result = bfsExplore();
cout << endl;
for (int i = 0; i < result.size(); ++i) {
if (i) cout << " ";
cout << result[i];
}
cout << endl;
}
};
int main() {
MagicalKingdom king;
king.readInput();
king.display();
return 0;
}