-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfs.c
136 lines (123 loc) · 2.23 KB
/
dfs.c
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include<stdio.h>
#include<stdlib.h>
struct node
{
int item;
struct node * next;
}* temp;
struct data
{
int entry;
int exit;
int visited;
int pred;
};
int clock;
struct node * makenode(int i,int x,struct node* A[])
{
struct node * ptr= malloc(sizeof(struct node));
if(ptr==NULL)
{
return ptr;
}
ptr->item=x;
ptr->next=NULL;
temp=A[i];
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
return ptr;
}
void DfsExplore(int v1,struct data * G[],struct node * A[])
{
G[v1]->visited=1;
G[v1]->entry=clock;
clock++;
int c=0;
struct node * temp=A[v1]->next;
while(temp!=NULL)
{
c++;
int x=temp->item;
if(G[x]->visited==0)
{
G[x]->pred=v1;
DfsExplore(x,G,A);
}
temp=temp->next;
}
G[v1]->exit=clock;
clock++;
}
void DepthFirstExpl(int v1,struct data * G[],struct node * A[],int n)
{
clock=0;
DfsExplore(v1,G,A);
for(int i=0;i<n;i++)
{
if(G[i]->visited==0)
{
DfsExplore(i,G,A);
}
}
}
void printdata(int n,struct data * G[])
{
for(int i=0;i<n;i++)
{
printf("%d %d\n",G[i]->entry,G[i]->exit);
}
}
int main()
{
int n,m,ind1,ind2;
struct node * abc;
scanf("%d",&n);
struct node* A[n];
scanf("%d",&m);
for(int k=0;k<n;k++)
{
A[k]=malloc(sizeof(struct node));
if(A[k]==NULL)
{
exit(1);
}
A[k]->item=k;
A[k]->next=NULL;
}
for(int k=0;k<m;k++)
{
scanf("%d",&ind1);
scanf("%d",&ind2);
abc=makenode(ind1,ind2,A);
if(abc==NULL)
{
exit(1);
}
abc=makenode(ind2,ind1,A);
if(abc==NULL)
{
exit(1);
}
}
int startingvertex;
scanf("%d",&startingvertex);
struct data * G[n];
for(int i=0;i<n;i++)
{
G[i]=malloc(sizeof(struct data));
if(G[i]==NULL)
{
exit(1);
}
G[i]->visited=0;
G[i]->entry=-1;
G[i]->exit=-1;
G[i]->pred=-1;
}
DepthFirstExpl(startingvertex,G,A,n);
printdata(n,G);
return 0;
}