Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

2. Implement function to print In-Degree, Out-Degree and to display that adjacency matrix. || DAA

#include <stdio.h> 

#define MAX_VERTICES 100 

typedef struct { 

int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES]; 

int numVertices; 

} Graph; 

void initGraph(Graph* g, int numVertices) { 

g->numVertices = numVertices; 

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

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

g->adjacencyMatrix[i][j] = 0; 

}  

void addEdge(Graph* g, int start, int end) { 

g->adjacencyMatrix[start][end] = 1; 

void displayGraph(Graph* g) { 

printf("Adjacency Matrix:\n"); 

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

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

printf("%d ", g->adjacencyMatrix[i][j]); 

printf("\n"); 

} } 

void calculateDegrees(Graph* g) 

{  

printf("Vertex\tIn-Degree\tOut-Degree\n");  

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

int inDegree = 0, outDegree = 0; 

for (int j = 0; j < g->numVertices; j++)  

inDegree += g->adjacencyMatrix[j][i];  

outDegree += g->adjacencyMatrix[i][j]; 

printf("%d\t%d\t\t%d\n", i, inDegree, outDegree); 

} } 

int main()  

{ Graph g; 

int numVertices, numEdges; 

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

scanf("%d", &numVertices); 

initGraph(&g, numVertices); 

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

scanf("%d", &numEdges); 

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

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

int start, end; 

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

addEdge(&g, start, end); 

displayGraph(&g); 

calculateDegrees(&g);

return 0;

}

Post a Comment

0 Comments