-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem86.cpp
More file actions
54 lines (47 loc) · 989 Bytes
/
problem86.cpp
File metadata and controls
54 lines (47 loc) · 989 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class CastlelandExplorer {
int n; // Number of castles
vector<vector<int>> adj; // Adjacency list
vector<bool> visited; // Visited flag
vector<int> order; // DFS order
public:
void readInput() {
cin >> n;
adj.resize(n);
visited.assign(n, false);
cin.ignore(); // clear newline
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);
}
}
}
void dfs(int u) {
visited[u] = true;
order.push_back(u);
for (int v : adj[u]) {
if (!visited[v]) {
dfs(v);
}
}
}
void display() {
dfs(0); // Start from castle 0
for (int i = 0; i < order.size(); ++i) {
if (i) cout << " ";
cout << order[i];
}
cout << endl;
}
};
int main() {
CastlelandExplorer explorer;
explorer.readInput();
explorer.display();
return 0;
}