Repository navigation
Expand file tree
/
Copy pathDFS.cpp
More file actions
173 lines (144 loc) · 3.01 KB
/
Copy pathDFS.cpp
File metadata and controls
173 lines (144 loc) · 3.01 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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
Program 15
Write a program to traverse the graph using DFS method.
*/
#include <iostream.h>
#include <conio.h>
#include <alloc.h>
#include <ctype.h>
struct graph
{
int node;
struct graph *down;
struct graph *next;
};
struct graph *start, *p, *q, *r, *s;
int stack[10], visit[10], tos = 0, count;
// Function to push node onto stack
void push(int x)
{
stack[tos] = x;
tos++;
if (visit[x] == 0)
{
visit[x] = 1;
count++;
}
}
// Function to pop node from stack
int pop()
{
int y;
tos--;
y = stack[tos];
return (y);
}
// Function to print the graph
void print()
{
p = q = start;
cout << "\nYour graph is:\n";
while (p != NULL)
{
cout << "\nParent Node " << p->node << " -> ";
q = p->next;
while (q != NULL)
{
cout << q->node << " ";
q = q->next;
}
p = p->down;
}
}
// DFS Traversal Function
void dfs()
{
int is, parent, flag;
r = p = q = s = start;
cout << "\n\nEnter the initial node: ";
cin >> is;
cout << "\nDFS Traversal: " << is << " ";
push(is);
while (tos != 1)
{
flag = 0;
parent = pop();
p = start;
while (p != NULL)
{
if (p->node == parent)
{
q = p->next;
while (q != NULL)
{
if (visit[q->node] == 0)
{
cout << q->node << " ";
push(p->node);
push(q->node);
flag = 1;
break;
}
else
q = q->next;
}
}
if (flag == 1)
break;
else
p = p->down;
}
}
cout << "\nTraversal Completed.\n";
}
// Function to create a graph node
struct graph *create()
{
struct graph *f;
f = (struct graph *)malloc(sizeof(struct graph));
f->next = NULL;
f->down = NULL;
cin >> f->node;
return (f);
}
// Main Function
void main()
{
int no;
char ch;
clrscr();
count = 0;
start = NULL;
cout << "Enter the graph structure for DFS traversal:\n";
do
{
cout << "\nEnter a parent node: ";
p = create();
if (start == NULL)
{
start = p;
r = q = p;
}
else
{
r->down = p;
r = p;
}
s = p;
cout << "Enter the adjacent nodes of " << p->node << ":\n";
do
{
cout << "Adjacent node: ";
q = create();
s->next = q;
s = q;
cout << "Continue adjacent nodes of " << p->node << "? (Y/N): ";
ch = getche();
} while (toupper(ch) == 'Y');
cout << "\nContinue entering parent nodes? (Y/N): ";
ch = getche();
} while (toupper(ch) == 'Y');
print();
dfs();
getch();
}