-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnum-disconnected-components-graph-dfs.cpp
More file actions
52 lines (40 loc) · 1 KB
/
num-disconnected-components-graph-dfs.cpp
File metadata and controls
52 lines (40 loc) · 1 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
// Program to find number of disconnected parts in graph
#include <vector>
#include <iostream>
using namespace std;
void dfs(int node, int visited[], vector<int> graph[]) {
visited[node] = 1;
for(int i = 0; i < graph[node].size(); i++) {
if(visited[graph[node][i]] == 0)
dfs(graph[node][i], visited, graph);
}
}
int num_connections(int n, vector<int> graph[]) {
int visited[n + 1];
for(int i = 0; i <= n; i++) {
visited[i] = 0;
}
int cc = 0;
for(int i = 1; i <= n; i++) {
if(visited[i] == 0) {
dfs(i, visited, graph);
cc++;
}
}
return cc;
}
int main() {
int n, m;
// Number of nodes and edges respectively
cin >> n >> m;
vector<int> graph[n + 1];
for(int j = 0; j < m; j++) {
int v1, v2;
// Vertices of edges
cin >> v1 >> v2;
graph[v1].push_back(v2);
graph[v2].push_back(v1);
}
cout << num_connections(n, graph) << endl;
return 0;
}