-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdfs.c
More file actions
77 lines (67 loc) · 1.21 KB
/
dfs.c
File metadata and controls
77 lines (67 loc) · 1.21 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
77
#include <stdio.h>
#include <stdlib.h>
void input(void);
int stackUnderflow(void);
int pop(void);
void push(int );
int v , arr[20][20] , stack[20] , visit[20] , start,top=-1;
void input(void)
{
for(int i = 0;i < v ; i++)
{
for(int j = 0 ; j < v ; j++)
scanf("%d",&arr[i][j]);
*(visit+i) = 0;
}
}
int pop(void){
int r;
r = stack[top];
top--;
return r;
}
void push(int pos){
top++;
stack[top] = pos;
visit[pos] = 1;
}
int stackUnderflow(void){
return top==-1 ? 1 : 0;
}
void dfs(){
printf("\nDFS of the graph : ");
push(start);
while(!stackUnderflow()){
int p = pop();
printf("%d ",p);
for(int i = 0 ; i < v ; i++){
if(arr[p][i]!=0 && visit[i]==0){
//printf("\n=======%d\n",i);
push(i);
}
}
}
}
int main()
{
printf("\nEnter total no of vertices : ");
scanf("%d",&v);
printf("\nEnter the adj matrix : \n");
input();
printf("\nEnter the starting vertex : ");
scanf("%d",&start);
dfs();
}
/*
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
0 1 1 0 0 0 0
1 0 0 1 1 0 0
1 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 1 0 0 0 0
*/