New

 #include <stdio.h>

#include <stdlib.h>


#define MAX_NODES 100


struct Graph {

    int numVertices;

    int adjMatrix[MAX_NODES][MAX_NODES];

};


void initGraph(struct Graph *graph, int numVertices) {

    graph->numVertices = numVertices;

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

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

            graph->adjMatrix[i][j] = 0;

        }

    }

}


void addEdge(struct Graph *graph, int src, int dest) {

    graph->adjMatrix[src][dest] = 1;

    graph->adjMatrix[dest][src] = 1; // For undirected graph

}


void BFS(struct Graph *graph, int startVertex) {

    int visited[MAX_NODES] = {0};

    int queue[MAX_NODES];

    int front = -1, rear = -1;

    

    visited[startVertex] = 1;

    queue[++rear] = startVertex;


    


    while (front != rear) {

        int currentVertex = queue[++front];

        


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

            if (graph->adjMatrix[currentVertex][i] == 1 && !visited[i]) {

                visited[i] = 1;

                queue[++rear] = i;

            }

        }

    }

    

}


void DFSUtil(struct Graph *graph, int vertex, int visited[]) {

    visited[vertex] = 1;

    


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

        if (graph->adjMatrix[vertex][i] == 1 && !visited[i]) {

            DFSUtil(graph, i, visited);

        }

    }

}


void DFS(struct Graph *graph, int startVertex) {

    int visited[MAX_NODES] = {0};


    

    DFSUtil(graph, startVertex, visited);

   

}


int main() {

    int numVertices, numEdges;

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

    scanf("%d", &numVertices);

    struct Graph graph;

    initGraph(&graph, numVertices);


    

    scanf("%d", &numEdges);


    

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

        int src, dest;

        scanf("%d %d", &src, &dest);

        addEdge(&graph, src, dest);

    }


    int startVertex;

   

    scanf("%d", &startVertex);


    BFS(&graph, startVertex);

    DFS(&graph, startVertex);


    return 0;

}

Post a Comment

0 Comments