aboutsummaryrefslogtreecommitdiff
path: root/src/graph.c
blob: 8c19a19d83111dddd97a86d8dcb5768385dea0f7 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "graph.h"
#include "vector.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

// Need to declare 'graph_delete' for use in 'graph_new'
void graph_delete(Graph *g);

Graph *graph_new(int n) {
    Graph *graph = (Graph *)malloc(sizeof(Graph));
    if (!graph)
        return NULL;

    graph->vertices = (Vertex *)malloc(sizeof(Vertex) * n);
    if (!graph->vertices) {
        free(graph);
        return NULL;
    }

    graph->num_edges = 0;
    graph->num_vertices = n;

    for (int i = 0; i < n; i++) {
        graph->vertices[i].id = i;
        graph->vertices[i].out_neighbours = vector_new();
        graph->vertices[i].in_neighbours = vector_new();

        // if allocation for the linked lists failed
        if (!graph->vertices[i].out_neighbours
            || !graph->vertices[i].in_neighbours) {
            graph_delete(graph);
            return NULL;
        }
    }

    return graph;
}

void graph_add_edge(Graph *g, int i, int j) {
    vector_push(g->vertices[i].out_neighbours, &g->vertices[j]);
    vector_push(g->vertices[j].in_neighbours, &g->vertices[i]);
    g->num_edges++;
}

Graph *graph_read(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (!file)
        return NULL;

    char line[4096];

    if (!fgets(line, sizeof(line), file)) {
        fclose(file);
        return NULL;
    }

    int n = atoi(line);
    if (n <= 0) {
        fclose(file);
        return NULL;
    }

    Graph *g = graph_new(n);
    if (!g) {
        fclose(file);
        return NULL;
    }

    for (int row = 0; row < n; row++) {
        if (!fgets(line, sizeof(line), file)) {
            fclose(file);
            return g;
        }

        int col = 0;
        for (int i = 0; line[i] != EOF && line[i] != '\n'; i++) {
            if (line[i] == '0' || line[i] == '1') {
                if (line[i] == '1')
                    graph_add_edge(g, row, col);
                col++;
            }
        }
    }

    fclose(file);
    return g;
}

void graph_print(Graph *g) {
    fprintf(stdout, "Number of vertices: %d\n", g->num_vertices);
    fprintf(stdout, "Number of edges: %d\n", g->num_edges);
}

void graph_delete(Graph *g) {
    for (int i = 0; i < g->num_vertices; i++) {
        vector_delete(g->vertices[i].in_neighbours);
        vector_delete(g->vertices[i].out_neighbours);
    }
    free(g->vertices);
    free(g);
}