-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path7.DFS.c
48 lines (43 loc) · 1.11 KB
/
7.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
// DFS traversal of a graph using stack as an auxiliary data structure
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
int cost[MAX_VERTICES][MAX_VERTICES], i, j, k, n, stk[MAX_VERTICES], top, v, visit[MAX_VERTICES], visited[MAX_VERTICES];
int main()
{
int m;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the number of edges: ");
scanf("%d", &m);
printf("\nEDGES:\n");
for (k = 1; k <= m; k++)
{
scanf("%d %d", &i, &j);
cost[i][j] = 1;
}
printf("Enter the initial vertex to traverse from: ");
scanf("%d", &v);
printf("DFS ORDER OF VISITED VERTICES: ");
printf("%d ", v); // visit the initial vertex
visited[v] = 1;
k = 1;
while (k < n)
{
for (j = n; j >= 1; j--)
{
if (cost[v][j] != 0 && visited[j] != 1 && visit[j] != 1)
{
visit[j] = 1;
stk[top] = j;
top++;
}
}
v = stk[--top];
printf("%d ", v);
k++;
visit[v] = 0;
visited[v] = 1;
}
return 0;
}