-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.c
More file actions
78 lines (61 loc) · 1.52 KB
/
bfs.c
File metadata and controls
78 lines (61 loc) · 1.52 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
75
76
77
78
#include <stdio.h>
#define MAX 20 // Maximum number of vertices
int queue[MAX];
int front = -1, rear = -1;
int visited[MAX];
// Function to add element to queue
void enqueue(int vertex) {
if (rear == MAX - 1) {
printf("Queue Overflow\n");
return;
}
if (front == -1)
front = 0;
queue[++rear] = vertex;
}
// Function to remove element from queue
int dequeue() {
if (front == -1 || front > rear)
return -1;
return queue[front++];
}
// Perform BFS on graph
void BFS(int adj[MAX][MAX], int n, int start) {
int i, current;
// Initialize visited array
for (i = 0; i < n; i++)
visited[i] = 0;
enqueue(start);
visited[start] = 1;
printf("BFS Traversal starting from vertex %d: ", start);
while (front <= rear) {
current = dequeue();
printf("%d ", current);
// Visit all adjacent vertices
for (i = 0; i < n; i++) {
if (adj[current][i] == 1 && visited[i] == 0) {
enqueue(i);
visited[i] = 1;
}
}
}
printf("\n");
}
// Main function
int main() {
int adj[MAX][MAX];
int n, start;
int i, j;
printf("Enter number of vertices: ");
scanf("%d", &n);
printf("Enter adjacency matrix (%d x %d):\n", n, n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &adj[i][j]);
}
}
printf("Enter starting vertex (0 to %d): ", n - 1);
scanf("%d", &start);
BFS(adj, n, start);
return 0;
}