-
Notifications
You must be signed in to change notification settings - Fork 1
/
dfs.cpp
82 lines (73 loc) · 1.33 KB
/
dfs.cpp
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
77
78
79
80
81
82
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
int v,edge,c,b,adj[100][100],dfstime=0,x,y,i;
struct vertex
{
char colour[6];
int p;
int f,d,key,small; }a[100];
void dfs_visit(vertex *g,int u)
{
dfstime=dfstime+1;
g[u].d=dfstime;
g[u].small=dfstime;
strcpy(g[u].colour,"gray");
for(int j=1;j<=v;j++)
{
if (adj[u][j]==1)
{
if(!strcmp(g[j].colour,"white"))
{
g[j].p=u;
dfs_visit(g,j);
if(!((g[j].small)<=g[u].d))
cout<<"BRIDGE : "<<g[j].key<<" "<<g[u].key<<"\n";
else
g[u].small=g[j].small;}
else
{
if(g[u].p!=j)
if(g[j].d<g[u].small)
g[u].small=g[j].small;}}
else
continue;
}
strcpy(g[u].colour,"black");
dfstime+=1;
g[u].f=dfstime;
}
void dfs(vertex *a)
{
for(i=1;i<=v;i++)
{
strcpy(a[i].colour,"white");
a[i].p=0;}
dfstime=0;
for(i=1;i<=v;i++)
{
if (!strcmp(a[i].colour,"white"))
dfs_visit(a,i);}}
int main()
{
cout<<"ENTER NO: OF VERTICES\n";
cin>>v;
cout<<"Enter no: of edges\n";
cin>>edge;
cout<<"enter edges as pair of vertices";
for(int k=1;k<=edge;k++)
{
cin>>c>>b;
adj[c][b]=1;
adj[b][c]=1;
}
cout<<"ENTER THE VERTICES\n";
for(int k=1;k<=v;k++)
cin>>a[k].key;
dfs(a);
cout<<"\nVertix\tStart Time\tFinishing Time\tColour";
for(i=1;i<=v;i++)
cout<<"\n"<<a[i].key<<"\t"<<a[i].d<<"\t "<<a[i].f<<"\t "<<a[i].colour;
return 0;
}