-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS_adj_mat.c
More file actions
74 lines (50 loc) · 1.18 KB
/
Copy pathBFS_adj_mat.c
File metadata and controls
74 lines (50 loc) · 1.18 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
#include <stdio.h>
#define MAX 100
int adj[MAX][MAX];
int visited[MAX];
int queue[MAX];
int front = 0, rear = 0;
void enqueue(int x) {
queue[rear++] = x;
}
int dequeue() {
return queue[front++];
}
int isEmpty() {
return front == rear;
}
void BFS(int start, int vertices) {
visited[start] = 1;
enqueue(start);
while (!isEmpty()) {
int node = dequeue();
printf("%d ", node);
for (int i = 0; i < vertices; i++) {
if (adj[node][i] == 1 && !visited[i]) {
visited[i] = 1;
enqueue(i);
}
}
}
}
int main() {
int vertices, edges;
printf("Enter number of vertices: ");
scanf("%d", &vertices);
for (int i = 0; i < vertices; i++) {
visited[i] = 0;
for (int j = 0; j < vertices; j++)
adj[i][j] = 0;
}
printf("Enter number of edges: ");
scanf("%d", &edges);
printf("Enter edges (u v):\n");
for (int i = 0; i < edges; i++) {
int u, v;
scanf("%d %d", &u, &v);
adj[u][v] = 1;
}
printf("BFS Traversal starting from 0:\n");
BFS(0, vertices);
return 0;
}