From 7a00f88749b00c7eb0404872b21e36adb17d8456 Mon Sep 17 00:00:00 2001 From: Mikkel Thestrup Date: Fri, 5 Dec 2025 11:33:16 +0100 Subject: Small changes --- src/cycle_detection.c | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) (limited to 'src/cycle_detection.c') diff --git a/src/cycle_detection.c b/src/cycle_detection.c index d232d89..8dd5691 100644 --- a/src/cycle_detection.c +++ b/src/cycle_detection.c @@ -9,12 +9,19 @@ void cycle_detection(Graph *g) { int n = g->num_vertices; int *indegree = calloc(n, sizeof(int)); + if (!indegree) { + fprintf(stderr, "Memory allocation failed: could not create list.\n"); + free(indegree); + return; + } + LinkedList *queue = linked_list_new(); if (!queue) { fprintf(stderr, "Memory allocation failed: could not create queue.\n"); free(indegree); return; } + Vector *list = vector_new(); if (!list) { fprintf(stderr, "Memory allocation failed: could not create vector.\n"); @@ -22,7 +29,7 @@ void cycle_detection(Graph *g) { linked_list_delete(queue); return; } - + // Compute in-degrees for (int i = 0; i < n; i++) { for (int j = 0; j < (int)g->vertices[i].out_neighbours->size; j++) { @@ -30,19 +37,19 @@ void cycle_detection(Graph *g) { indegree[neighbor]++; } } - + // Add all vertices with no incoming edges for (int i = 0; i < n; i++) { - if (!indegree[i]) { + if (indegree[i] == 0) { linked_list_append(queue, (void *)(intptr_t)i); } } - + // Process queue for topological sort - while (queue->size) { + while (queue->size != 0) { int top = (int)(intptr_t)linked_list_popfront(queue); vector_push(list, (void *)(intptr_t)top); - + // Process all neighbors of current vertex for (int j = 0; j < (int)g->vertices[top].out_neighbours->size; j++) { int neighbor = *(int *)g->vertices[top].out_neighbours->data[j]; @@ -52,11 +59,11 @@ void cycle_detection(Graph *g) { } } } - + // Output result - if ((int)list->size != n) { + if ((int)list->size != n) fprintf(stdout, "CYCLE DETECTED!\n"); - } else { + else { for (int i = 0; i < (int)list->size; i++) { if (i != 0) fprintf(stdout, ", "); @@ -64,7 +71,7 @@ void cycle_detection(Graph *g) { } fprintf(stdout, "\n"); } - + linked_list_delete(queue); vector_delete(list); free(indegree); -- cgit v1.2.3-70-g09d2