-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdfs_stack.c
130 lines (101 loc) · 1.83 KB
/
dfs_stack.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
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define ROW 100
#define COL 100
int matrix[ROW][COL];
int visited[ROW];
int num;
int Stack[MAX];
int f;
int pop(void)
{
if (IsStackEmpty())
return -1;
else {
int element = Stack[f];
f--;
return element;
}
}
void push(int element)
{
if(IsStackFull())
return;
else {
Stack[++f] = element;
}
}
int IsStackEmpty(void)
{
if (f==-1)
return 1;
else
return 0;
}
int IsStackFull(void)
{
if (f == MAX-1)
return 1;
else return 0;
}
int peek(void)
{
return Stack[f];
}
/*
DFS(int node)
{
int count = 0;
printf("Node [%d]", node);
arr[node] = GREY;
for (; count <num; count++) {
if (matrix[node][count] == 0)
continue;
if (arr[count] == WHITE)
DFS(count);
}
}
*/
void DFS()
{
while(!IsStackEmpty()) {
int element = peek();
int k;
int childfound = 0;
for(k=0; k < num; k++) {
if (matrix[element][k] == 1 && visited[k] != 1) {
visited[k] = 1;
printf("Element [%d]\n", k);
push(k);
childfound = 1;
break;
}
}
if (!childfound)
pop();
}
}
int main()
{
int r, c, count;
f = -1;
printf("Enter Number of nodes in your graph..");
scanf("%d", &num);
for (r=0; r < num; r++) {
for (c = 0; c< num; c++) {
scanf("%d", &matrix[r][c]);
}
}
for (r=0; r < num; r++) {
for (c = 0; c< num; c++) {
printf("[%d]", matrix[r][c]);
}
printf("\n");
}
for (count =0; count < num; count++)
visited[count] = 0;
push(0);
visited[0] = 1;
DFS();
}