forked from MohmedIkram/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS_graph.c
107 lines (100 loc) · 1.93 KB
/
DFS_graph.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
#include <stdio.h>
#include <stdlib.h>
// #include <conio.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *insert(node *root)
{
int j = 0;
while (1)
{
printf("\nEnter the adjacancy node number OR enter -1 to stop : ");
scanf("%d", &j);
if (j == -1)
{
break;
}
node *p = (node *)malloc(sizeof(node));
p->data = j;
p->next = NULL;
if (root == NULL)
{
root = p;
}
else
{
p->next = root;
root = p;
}
}
return root;
}
void print(node *p)
{
while (p != NULL)
{
printf("%d->", p->data);
p = p->next;
}
}
void DFS_visit(node **graph, int *color, int i)
{
if (graph[i] != NULL)
{
int k = graph[i]->data;
node *temp = graph[i];
while (temp != NULL)
{
if (color[k] == 0)
{
printf("%d ,", k);
color[k] = 1;
DFS_visit(graph, color, k);
}
temp = temp->next;
if (temp != NULL)
k = temp->data;
}
}
}
void DFS(node **graph, int *color, int n)
{
for (int i = 0; i < n; i++)
{
if (color[i] == 0)
{
printf("%d ,", i);
color[i] = 1;
DFS_visit(graph, color, i);
}
}
}
int main()
{
node *graph[20];
int n;
printf("\nEnetr the number of nodes : ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("\ninsert the adjaceency nodes in the graph for node %d", i);
graph[i] = NULL;
graph[i] = insert(graph[i]);
}
for (int i = 0; i < n; i++)
{
printf("%d->", i);
print(graph[i]);
printf("\n");
}
int color[n];
for (int i = 0; i < n; i++)
{
color[i] = 0;
}
DFS(graph, color, n);
return 0;
}