// Allocate memory for adjacency matrix graph->matrix = (int**)malloc(vertices * sizeof(int*)); for (int i = 0; i < vertices; ++i) { graph->matrix[i] = (int*)calloc(vertices, sizeof(int)); }
return graph; }
voidaddEdgeAdjMatrix(GraphAdjMatrix* graph, int src, int dest) { // Assuming it's an undirected graph, assigning 1 for both directions graph->matrix[src][dest] = 1; graph->matrix[dest][src] = 1; }
voidprintGraphAdjMatrix(GraphAdjMatrix* graph) { printf("Adjacency Matrix:\n"); for (int i = 0; i < graph->V; ++i) { for (int j = 0; j < graph->V; ++j) { printf("%d ", graph->matrix[i][j]); } printf("\n"); } }
voidfreeGraphAdjMatrix(GraphAdjMatrix* graph) { for (int i = 0; i < graph->V; ++i) { free(graph->matrix[i]); } free(graph->matrix); free(graph); }
intmain() { int V = 4; // Number of vertices GraphAdjMatrix* g = createGraphAdjMatrix(V);
// Create an array of adjacency lists graph->array = (Node**)malloc(vertices * sizeof(Node*)); for (int i = 0; i < vertices; ++i) { graph->array[i] = NULL; }
return graph; }
voidaddEdgeAdjList(GraphAdjList* graph, int src, int dest) { // Add edge from src to dest Node* newNode = createNode(dest); newNode->next = graph->array[src]; graph->array[src] = newNode;
// For undirected graph, uncomment the lines below /* newNode = createNode(src); newNode->next = graph->array[dest]; graph->array[dest] = newNode; */ }
voidprintGraphAdjList(GraphAdjList* graph) { printf("Adjacency List:\n"); for (int i = 0; i < graph->V; ++i) { Node* temp = graph->array[i]; printf("Adjacency list of vertex %d: ", i); while (temp != NULL) { printf("%d -> ", temp->dest); temp = temp->next; } printf("NULL\n"); } }
voidfreeGraphAdjList(GraphAdjList* graph) { for (int i = 0; i < graph->V; ++i) { Node* current = graph->array[i]; while (current != NULL) { Node* next = current->next; free(current); current = next; } } free(graph->array); free(graph); }
intmain() { int V = 4; // Number of vertices GraphAdjList* g = createGraphAdjList(V);