-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfs.c
87 lines (82 loc) · 1.04 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
#include<stdio.h>
#define initial 0
#define waiting 1
#define visited 2
#define MAX 15
int g[20][20],stack[20],s[20];
int top=-1,n;
void dfs(int);
int empty();
int pop();
void push(int);
main()
{
int e,u,v,i,j;
printf("Enter no of vertex and edges\n");
scanf("%d%d",&n,&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
g[i][j]=0;
}
}
for(i=1;i<=e;i++)
{
printf("Enter 1st and end vertex\n");
scanf("%d%d",&u,&v);
g[u][v]=g[v][u]=1;
}
for(i=1;i<=n;i++)
s[i]=initial;
dfs(1);
}
void dfs(int v)
{
int x,i;
push(v);
s[v]=waiting;
while(!empty())
{
x=pop();
printf("%d",x);
s[x]=visited;
for(i=1;i<=n;i++)
{
if(g[x][i]!=0 && s[i]==initial)
{
push(i);
s[i]=waiting;
}
}
}
}
int empty()
{
if(top==-1)
return -1;
else
return 0;
}
void push(int v)
{
if(top==MAX-1)
printf("full");
else
{
top++;
stack[top]=v;
}
}
int pop()
{
int x;
if(top==-1)
return -1;
else
{
x=stack[top];
top--;
return x;
}
}