-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.c
158 lines (133 loc) · 3.06 KB
/
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
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
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
typedef struct Node {
int vertex;
struct Node *next;
} Node;
typedef struct Queue {
int data[MAX];
int front, rear;
} Queue;
void enqueue(Queue *, int);
int dequeue(Queue *);
int isEmpty(Queue *);
void readGraph();
void insert(int, int);
void DFS(int);
void BFS(int);
Node *G[MAX];
int n, visited[MAX];
void readGraph() {
int i, vi, vj, edges;
printf("\nEnter number of vertices: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
G[i] = NULL;
for (i = 0; i < n; i++) {
printf("\nEnter number of edges: ");
scanf("%d", &edges);
for (i = 0; i < edges; i++) {
printf("\nEnter an edge (u, v): ");
scanf("%d %d", &vi, &vj);
insert(vi, vj);
}
}
}
void insert(int vi, int vj) {
Node *p, *q;
q = (Node *)malloc(sizeof(Node));
q->vertex = vj;
q->next = NULL;
if (G[vi] == NULL)
G[vi] = q;
else {
p = G[vi];
while (p->next != NULL)
p = p->next;
p->next = q;
}
}
void DFS(int i) {
Node *p;
printf(" %d", i);
p = G[i];
visited[i] = 1;
while (p != NULL) {
i = p->vertex;
if (!visited[i])
DFS(i);
p = p->next;
}
}
void BFS(int v) {
int i, w;
Queue q;
Node *p;
q.front = q.rear = -1;
for (i = 0; i < n; i++)
visited[i] = 0;
enqueue(&q, v);
printf("\nVisit\t%d", v);
visited[v] = 1;
while (!isEmpty(&q)) {
v = dequeue(&q);
for (p = G[v]; p != NULL; p = p->next) {
w = p->vertex;
if (!visited[w]) {
enqueue(&q, w);
visited[w] = 1;
printf("\nVisit\t%d", w);
}
}
}
}
int isEmpty(Queue *q) {
return q->front == -1;
}
void enqueue(Queue *q, int x) {
if (q->rear == -1) {
q->front = q->rear = 0;
q->data[q->rear] = x;
} else {
q->rear++;
q->data[q->rear] = x;
}
}
int dequeue(Queue *q) {
int x;
x = q->data[q->front];
if (q->rear == q->front) {
q->rear = -1;
q->front = -1;
} else {
q->front++;
}
return x;
}
int main() {
int op;
printf("Arya Joshi\n60019220020");
do {
printf("\n 1) Create 2) BFS 3) DFS 4) Quit\n");
scanf("%d", &op);
switch (op) {
case 1:
readGraph();
break;
case 2:
printf("\n Enter starting node number: ");
scanf("%d", &op);
BFS(op);
break;
case 3:
for (op = 0; op < n; op++)
visited[op] = 0;
printf("\n Enter starting node number: ");
scanf("%d", &op);
DFS(op);
break;
}
} while (op != 4);
return 0;
}