-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdfs.cpp
More file actions
41 lines (31 loc) · 714 Bytes
/
dfs.cpp
File metadata and controls
41 lines (31 loc) · 714 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
#include <iostream>
#include <vector>
using namespace std;
const int N = 1e5;
int n_nodes, n_edges;
vector<int> g[N];
bool visited[N];
void dfs(int node) {
// cout << node << endl; // for tracing
visited[node] = true;
for (int neg : g[node]) {
if (!visited[neg])
dfs(neg);
}
}
int main() {
cout << "Enter n_nodes and n_edges: ", cin >> n_nodes >> n_edges;
// Read input for graph
for (int i = 0; i < n_edges; i++)
{
int n1, n2;
cin >> n1 >> n2;
g[n1].push_back(n2);
g[n2].push_back(n1);
}
// dfs
for (int i = 1; i <= n_nodes; i++)
if (!visited[i])
dfs(i);
return 0;
}