From 64e0ffc682de88d588472924ca42fc6c804daebd Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Wed, 18 Jan 2023 17:33:33 +0700 Subject: [PATCH] WIP graph implementation --- TheAlgorithmDesignManual.org | 65 ++++++++++++++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/TheAlgorithmDesignManual.org b/TheAlgorithmDesignManual.org index 44fb680..f2dbc9b 100644 --- a/TheAlgorithmDesignManual.org +++ b/TheAlgorithmDesignManual.org @@ -781,9 +781,70 @@ operations. Use linked lists instead, however it is harder to verify if a certain edge exists. This can be mitigated by collecting them in a BFS of DFS. -#+begin_src C :includes stdio.h stdlib.h -//TODO Copy graph implementation +#+begin_src C :includes stdio.h stdlib.h stdbool.h +#define MAXV 1000 + +struct edgenode { + int y; + int weight; + struct edgenode *next; +}; + +struct graph { + struct edgenode *edges[MAXV+1]; + int degree[MAXV+1]; + int nvertices; + int nedges; + bool directed; +}; + +void initialize_graph(struct graph *g, bool directed) { + g->nvertices = 0; + g->nedges = 0; + g->directed = directed; + for (int i = 1; i <= MAXV; i++) g->degree[i] = 0; + for (int i = 1; i <= MAXV; i++) g->edges[i] = NULL; +} + +// TODO: We have to read whether the graph is directed or not and +// insert edges twice +void insert_edge(struct graph *g, int x, int y) { + struct edgenode *p; + p = malloc(sizeof(struct edgenode)); + p->weight = 0; + p->y = y; + p->next = g->edges[x]; + + g->edges[x] = p; + g->degree[x]++; + + if (g->directed == false) { + insert_edge(g, y, x); + } +} + +void print_graph(struct graph *g) { + int i; + struct edgenode *p; + + for (i = 0; i <= g->nvertices; i++) { + printf("V%d", i); + p = g->edges[i]; + while (p != NULL) { + printf("->%d", p->y); + p = p->next; + } + printf("\n"); + } +} + +struct graph *g = malloc(sizeof(struct graph)); +initialize_graph(g, true); +print_graph(g); #+end_src +#+RESULTS: +: V0 + ** 5.3 War Story