diff options
| author | Mikkel Thestrup <mithe24@student.sdu.dk> | 2025-12-05 11:33:16 +0100 |
|---|---|---|
| committer | Mikkel Thestrup <mithe24@student.sdu.dk> | 2025-12-05 11:41:09 +0100 |
| commit | 7a00f88749b00c7eb0404872b21e36adb17d8456 (patch) | |
| tree | 51c387c8a46b80984526aea74b4e4d703bf15bea /src/cycle_detection.c | |
| parent | f624eaf7cb786fea5e574637ccd31fbed52eec5a (diff) | |
| download | cycle-detector-7a00f88749b00c7eb0404872b21e36adb17d8456.tar.gz cycle-detector-7a00f88749b00c7eb0404872b21e36adb17d8456.zip | |
Small changes
Diffstat (limited to '')
| -rw-r--r-- | src/cycle_detection.c | 27 |
1 files changed, 17 insertions, 10 deletions
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); |