forked from Coder-forfun/Hactoberfest-accepted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.c
104 lines (97 loc) · 1.78 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//DFS
#include <stdio.h>
#include <stdlib.h>
//Queue
struct Node
{
int data;
struct Node *next;
} *front = NULL, *rear = NULL;
int isEmpty()
{
if (front == NULL)
{
return 1;
}
return 0;
}
void enqueue(int x)
{
struct Node *t;
t = (struct Node *)malloc(sizeof(struct Node));
if (t == NULL)
{
printf("Queue is full\n");
}
else
{
t->data = x;
t->next = NULL;
if (front == NULL)
{
front = rear = t;
}
else
{
rear->next = t;
rear = t;
}
}
}
int dequeue()
{
int x = -1;
struct Node *t;
if (front == NULL)
{
printf("Queue is empty");
}
{
x = front->data;
t = front;
front = front->next;
free(t);
}
return x;
}
//Implementation of Depth First Search
void DFS(int G[][7], int start, int n)
{
static int visited[7] = {0};
if (visited[start] == 0)
{
visited[start] = 1;
printf("%d ", start);
for (int j = 1; j < n; j++)
{
if (G[start][j] == 1 && visited[j] == 0)
{
DFS(G, j, n);
}
}
}
}
int main()
{
// Adjacency matrix
int G[7][7] = {
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0},
{0, 1, 0, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 0, 0},
{0, 0, 1, 1, 0, 1, 1},
{0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 1, 0, 0},
};
// Graph
// 1
// / \
// 2 3
// \ /
// 4
// / \
// 5 6
DFS(G, 1, 7);
return 0;
}
// Contributed by Mayankesh Jha