-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdfs.cpp
More file actions
40 lines (32 loc) · 759 Bytes
/
Copy pathdfs.cpp
File metadata and controls
40 lines (32 loc) · 759 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
#include <iostream>
#include <vector>
using namespace std;
void dfs(const vector<vector<int>>& graph,
int vertex,
vector<bool>& visited,
vector<int>& order) {
visited[vertex] = true;
order.push_back(vertex);
for (int neighbor : graph[vertex]) {
if (!visited[neighbor]) {
dfs(graph, neighbor, visited, order);
}
}
}
int main() {
vector<vector<int>> graph = {
{1, 2},
{0, 3, 4},
{0, 5},
{1},
{1},
{2}
};
vector<bool> visited(graph.size(), false);
vector<int> order;
dfs(graph, 0, visited, order);
cout << "DFS traversal: ";
for (int vertex : order) cout << vertex << ' ';
cout << '\n';
return 0;
}