topological sort P6

 #include <stdio.h>

#include <stdlib.h>


#define MAX_VERTICES 100


// Structure to represent a graph

typedef struct {

    int V;

    int** adjMatrix;

} Graph;


// Function to create a new graph

Graph* createGraph(int V) {

    Graph* graph = (Graph*)malloc(sizeof(Graph));

    graph->V = V;

    graph->adjMatrix = (int**)calloc(V, sizeof(int*));

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

        graph->adjMatrix[i] = (int*)calloc(V, sizeof(int));

    }

    return graph;

}


// Function to add an edge to the graph

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

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

}


// Function to perform topological sorting

void topologicalSort(Graph* graph) {

    int V = graph->V;

    int inDegree[MAX_VERTICES] = {0};

    int queue[MAX_VERTICES], front = 0, rear = -1;


    // Calculate in-degree (number of incoming edges) for each vertex

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

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

            if (graph->adjMatrix[i][j] == 1) {

                inDegree[j]++;

            }

        }

    }


    // Enqueue all vertices with in-degree 0

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

        if (inDegree[i] == 0) {

            queue[++rear] = i;

        }

    }


    printf("Topological ordering of vertices: ");

    

    // Process until the queue is empty

    while (front <= rear) {

        int vertex = queue[front++];

        printf("%d ", vertex);


        // Reduce the in-degree of all adjacent vertices

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

            if (graph->adjMatrix[vertex][i] == 1 && --inDegree[i] == 0) {

                queue[++rear] = i;

            }

        }

    }

    printf("\n");

}


// Driver code

int main() {

    int V, E;

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

    scanf("%d", &V);


    if (V > MAX_VERTICES) {

        printf("Error: Number of vertices exceeds the maximum limit of %d.\n", MAX_VERTICES);

        return 1;

    }


    Graph* graph = createGraph(V);


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

    scanf("%d", &E);


    printf("Enter the edges (source vertex, destination vertex):\n");

    for (int i = 0, src, dest; i < E; i++) {

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

        addEdge(graph, src, dest);

    }


    topologicalSort(graph);


    // Free allocated memory

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

        free(graph->adjMatrix[i]);

    }

    free(graph->adjMatrix);

    free(graph);


    return 0;

}


Comments

Popular posts from this blog

kruskal algo P4

prim's algo P5