-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdfs_undirected.cpp
More file actions
56 lines (47 loc) · 1.08 KB
/
Copy pathdfs_undirected.cpp
File metadata and controls
56 lines (47 loc) · 1.08 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
53
54
55
56
/*Doing it for un-directed graph*/
#include<iostream>
#include<vector>
#define MAX 50
using namespace std ;
vector <int> adj[MAX] ;
bool visited[MAX] ;
/*Initialize the boolean values to the visited part ..Since no nodes got traversed till now */
void initialize(int nodes)
{
for (int i = 1 ; i<=nodes ;i++){
visited[i] = false ;
}
}
//to perform depth first search
void dfs(int current)
{
cout << current << "\t";
visited[current] = true ;
for(int i = 0 ; i< adj[current].size() ; i++){
if (visited[adj[current][i]] == false){
dfs(adj[current][i]) ;
}
}
}
int main ()
{
int nodes , edges , x , y , i ;
cout << "Enter the total nodes in the graph\t" ;
cin >> nodes ;
cout << "Enter the total edges of the graph\t" ;
cin >> edges ;
cout << "Enter the edges pairs of the graph (eg : a b)for a->b)\n" ;
for (i = 0 ; i <edges ; i++){
cin >> x >> y ;
adj[x].push_back(y);
adj[y].push_back(x);
}
initialize(nodes) ;
cout << "The dfs traversal sequence is given as\n" ;
for (i = 1 ; i<=nodes ; i++){
if(visited[i] == false){
dfs(i);
}
}
return 0 ;
}