Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create BFS.c #405

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions C/BFS.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

// Structure for the queue
typedef struct {
int items[MAX];
int front, rear;
} Queue;

// Function to create a queue
Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = -1;
q->rear = -1;
return q;
}

// Function to check if the queue is empty
int isEmpty(Queue* q) {
return q->front == -1;
}

// Function to enqueue an element
void enqueue(Queue* q, int value) {
if (q->rear == MAX - 1) {
printf("Queue is full\n");
return;
}
if (q->front == -1) {
q->front = 0; // First element to be enqueued
}
q->rear++;
q->items[q->rear] = value;
}

// Function to dequeue an element
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
}
int item = q->items[q->front];
q->front++;
if (q->front > q->rear) { // Reset the queue
q->front = q->rear = -1;
}
return item;
}

// Function to perform BFS
void bfs(int graph[MAX][MAX], int start, int visited[MAX], int n) {
Queue* q = createQueue();
enqueue(q, start);
visited[start] = 1; // Mark the starting node as visited

while (!isEmpty(q)) {
int current = dequeue(q);
printf("%d ", current); // Process the current node

// Explore neighbors
for (int i = 0; i < n; i++) {
if (graph[current][i] == 1 && !visited[i]) { // If edge exists and not visited
enqueue(q, i);
visited[i] = 1; // Mark neighbor as visited
}
}
}

free(q);
}

int main() {
int graph[MAX][MAX] = {
{0, 1, 1, 0, 0},
{1, 0, 0, 1, 0},
{1, 0, 0, 0, 1},
{0, 1, 0, 0, 1},
{0, 0, 1, 1, 0}
};

int visited[MAX] = {0}; // Visited array
int n = 5; // Number of vertices

printf("BFS Traversal starting from vertex 0:\n");
bfs(graph, 0, visited, n);

return 0;
}