-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.cpp
More file actions
76 lines (61 loc) · 1.38 KB
/
DFS.cpp
File metadata and controls
76 lines (61 loc) · 1.38 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
67
68
69
70
71
72
73
74
75
76
#include<bits/stdc++.h>
using namespace std;
#define WHITE 1
#define GRAY 2
#define BLACK 3
#define size 30
int adj[size][size], color[size],d[size], f[size],prev[size];
int Time, vertex, edge;
void DFS_Visit(int u){
color[u] = GRAY;
Time = Time + 1;
d[u] = Time;
for(int v = 0; v < vertex; v++){
if(adj[u][v] == 1){
if(color[v] == WHITE){
prev[v] = u;
DFS_Visit(v);
}
}
}
color[u] = BLACK;
Time = Time + 1;
f[u] = Time;
}
void DFS(){
for(int u=0; u<vertex; u++){
color[u] = WHITE;
prev[u]=-1;
d[u] = INT_MAX;
f[u] = INT_MAX;
}
for(int u=0; u<vertex; u++){
if(color[u] == WHITE){
DFS_Visit(u);
}
}
}
void DFS_Display()
{
for(int i=0; i < vertex; i++){
cout<<"Vertex :"<<(char)('A' + i);
if(prev[i] == -1)
cout<<" Previous Vertex -> null";
else
cout<<" Previous->"<<(char)('A' + prev[i]);
cout<<" Discovery Time ->"<<d[i]<<" Finishing Time ->"<<f[i]<<endl;
}
}
int main()
{
freopen("in.txt","r",stdin);
cin>>vertex>>edge;
int v1,v2;
for(int i=0; i < edge; i++){
cin>>v1>>v2;
adj[v1][v2] = 1;
}
DFS();
DFS_Display();
return 0;
}