-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.cpp
More file actions
66 lines (54 loc) · 1 KB
/
DFS.cpp
File metadata and controls
66 lines (54 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
edges = 3 ,vertex = 4
Enter the edges :
0 1
0 2
2 3
*/
#include<bits/stdc++.h>
#define white 1
#define gray 2
#define black 3
#define pb push_back
using namespace std;
vector<int> color;
vector<vector<int> > g;
int v,e;
void DFS_Visit(int s)
{
color[s] = gray;
cout<<" "<<s<<endl;
for(int i=0;i<g[s].size();i++){
int v = g[s][i];
if(color[v]==white){
DFS_Visit(v);
}
}
color[s] = black;
}
void DFS(int SN)
{
if(color[SN] == white )
DFS_Visit(SN);
for(int i = 0 ; i<v ; i++){
if(color[i] == white){
DFS_Visit(i);
}
}
}
int main()
{
cout<<"Enter the number the edges and vertex : ";
cin>>e>>v;
color.assign(v,white);
g.assign(v,vector<int>());
int n1,n2;
cout<<"Enter the edges : "<<endl;
for(int i = 0 ; i<e ; i++){
cin>>n1>>n2;
g[n1].pb(n2);
g[n2].pb(n1);
}
DFS(0);
return 0;
}