WIP graph implementation

This commit is contained in:
Joseph Ferano 2023-01-18 17:33:33 +07:00
parent d76abc5ea9
commit 64e0ffc682

View File

@ -781,9 +781,70 @@ operations.
Use linked lists instead, however it is harder to verify if a certain edge 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. exists. This can be mitigated by collecting them in a BFS of DFS.
#+begin_src C :includes stdio.h stdlib.h #+begin_src C :includes stdio.h stdlib.h stdbool.h
//TODO Copy graph implementation #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 #+end_src
#+RESULTS:
: V0
** 5.3 War Story ** 5.3 War Story