DFS And BFS Traversal

#include <stdio.h>

#include <stdlib.h>


// Define the maximum number of vertices in the graph

#define MAX_VERTICES 100


// Define a stack for DFS and a queue for BFS

int stack[MAX_VERTICES];

int top = -1;

int queue[MAX_VERTICES];

int front = -1, rear = -1;


int visited[MAX_VERTICES];


// Define the adjacency matrix for the graph

int graph[MAX_VERTICES][MAX_VERTICES];

int numVertices;


void push(int vertex) {

    stack[++top] = vertex;

}


int pop() {

    return stack[top--];

}


void enqueue(int vertex) {

    if (rear == MAX_VERTICES - 1)

        printf("Queue is full.\n");

    else

        queue[++rear] = vertex;

}


int dequeue() {

    if (front == rear)

        return -1; // Empty queue

    return queue[++front];

}


void initGraph(int vertices) {

    numVertices = vertices;

    for (int i = 0; i < numVertices; i++) {

        visited[i] = 0;

        for (int j = 0; j < numVertices; j++) {

            graph[i][j] = 0;

        }

    }

}


void addEdge(int start, int end) {

    graph[start][end] = 1;

}


void DFS(int vertex) {

    int u, v;

    push(vertex);


    while (top != -1) {

        u = pop();

        if (visited[u] == 0) {

            printf("Visited vertex %d\n", u);

            visited[u] = 1;

            for (v = 0; v < numVertices; v++) {

                if (graph[u][v] && !visited[v]) {

                    push(v);

                }

            }

        }

    }

}


void BFS(int vertex) {

    int u, v;

    enqueue(vertex);


    while (front != rear) {

        u = dequeue();

        if (visited[u] == 0) {

            printf("Visited vertex %d\n", u);

            visited[u] = 1;

            for (v = 0; v < numVertices; v++) {

                if (graph[u][v] && !visited[v]) {

                    enqueue(v);

                }

            }

        }

    }

}


int main() {

    int vertices, edges, startVertex;

   

    printf("Enter the number of vertices and edges: ");

    scanf("%d %d", &vertices, &edges);

    initGraph(vertices);

   

    printf("Enter the edges (format: start end):\n");

    for (int i = 0; i < edges; i++) {

        int start, end;

        scanf("%d %d", &start, &end);

        addEdge(start, end);

    }

   

    printf("Enter the starting vertex for traversal: ");

    scanf("%d", &startVertex);

   

    printf("DFS Traversal:\n");

    DFS(startVertex);

   

    // Reset visited array

    for (int i = 0; i < vertices; i++) {

        visited[i] = 0;

    }


    printf("\nBFS Traversal:\n");

    BFS(startVertex);

   

    return 0;

}


Previous Post Next Post