aboutsummaryrefslogtreecommitdiff
path: root/src/cycle_detection.c
blob: d232d89c7c45e3064c0f226c7e52c41d9d02f51a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "cycle_detection.h"
#include "graph.h"
#include "linked_list.h"
#include "vector.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

void cycle_detection(Graph *g) {
    int n = g->num_vertices;
    int *indegree = calloc(n, sizeof(int));
    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");
        free(indegree);
        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++) {
            int neighbor = *(int *)g->vertices[i].out_neighbours->data[j];
            indegree[neighbor]++;
        }
    }
    
    // Add all vertices with no incoming edges
    for (int i = 0; i < n; i++) {
        if (!indegree[i]) {
            linked_list_append(queue, (void *)(intptr_t)i);
        }
    }
    
    // Process queue for topological sort
    while (queue->size) {
        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];
            indegree[neighbor]--;
            if (!indegree[neighbor]) {
                linked_list_append(queue, (void *)(intptr_t)neighbor);
            }
        }
    }
    
    // Output result
    if ((int)list->size != n) {
        fprintf(stdout, "CYCLE DETECTED!\n");
    } else {
        for (int i = 0; i < (int)list->size; i++) {
            if (i != 0)
                fprintf(stdout, ", ");
            fprintf(stdout, "%d", (int)(intptr_t)vector_get(list, i));
        }
        fprintf(stdout, "\n");
    }
    
    linked_list_delete(queue);
    vector_delete(list);
    free(indegree);
}