-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.cpp
More file actions
40 lines (31 loc) · 696 Bytes
/
DFS.cpp
File metadata and controls
40 lines (31 loc) · 696 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 <bits/stdc++.h>
#define MAX 100005
using namespace std;
bool visited[MAX];
vector<vector<int> >v;
void dfs(int num) {
visited[num] = true;
for (auto it : v[num])
if(!visited[it])
dfs(it);
}
int main() {
int V, E, x, y, count = 0;
cout << "Enter the no. of vertices and edges : ";
cin >> V >> E;
v.resize(V+1); v.clear();
memset(visited,0,sizeof visited);
cout << "Enter the edges :\n";
for(int i = 0; i < E; i++) {
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x); //Considering undirected graph ATM
}
for(int i = 0; i < V; i++) {
if(!visited[i]) {
dfs(i);
count ++;
}
}
cout << "Number of connected components are : " << count << endl;
}