-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.c
642 lines (522 loc) · 16.6 KB
/
Graph.c
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//
// Algoritmos e Estruturas de Dados --- 2024/2025
//
// Joaquim Madeira, Joao Manuel Rodrigues - June 2021, Nov 2023, Nov/Dec 2024
//
// Graph - Using a list of adjacency lists representation
//
// Student Name : Filipe Viseu
// Student Number : 119192
// Student Name : Duarte Branco
// Student Number : 119253
/*** COMPLETE THE GraphCreateTranspose FUNCTION ***/
#include "Graph.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "SortedList.h"
struct _Vertex {
unsigned int id;
unsigned int inDegree;
unsigned int outDegree;
List* edgesList;
};
struct _Edge {
unsigned int adjVertex;
double weight;
};
struct _GraphHeader {
int isDigraph;
int isComplete;
int isWeighted;
unsigned int numVertices;
unsigned int numEdges;
List* verticesList;
};
// The comparator for the VERTICES LIST
int graphVerticesComparator(const void* p1, const void* p2) {
unsigned int v1 = ((struct _Vertex*)p1)->id;
unsigned int v2 = ((struct _Vertex*)p2)->id;
int d = v1 - v2;
return (d > 0) - (d < 0);
}
// The comparator for the EDGES LISTS
int graphEdgesComparator(const void* p1, const void* p2) {
unsigned int v1 = ((struct _Edge*)p1)->adjVertex;
unsigned int v2 = ((struct _Edge*)p2)->adjVertex;
int d = v1 - v2;
return (d > 0) - (d < 0);
}
Graph* GraphCreate(unsigned int numVertices, int isDigraph, int isWeighted) {
Graph* g = (Graph*)malloc(sizeof(struct _GraphHeader));
if (g == NULL) abort();
g->isDigraph = isDigraph;
g->isComplete = 0;
g->isWeighted = isWeighted;
g->numVertices = numVertices;
g->numEdges = 0;
g->verticesList = ListCreate(graphVerticesComparator);
for (unsigned int i = 0; i < numVertices; i++) {
struct _Vertex* v = (struct _Vertex*)malloc(sizeof(struct _Vertex));
if (v == NULL) abort();
v->id = i;
v->inDegree = 0;
v->outDegree = 0;
v->edgesList = ListCreate(graphEdgesComparator);
ListInsert(g->verticesList, v);
}
assert((int)g->numVertices == ListGetSize(g->verticesList));
return g;
}
Graph* GraphCreateComplete(unsigned int numVertices, int isDigraph) {
Graph* g = GraphCreate(numVertices, isDigraph, 0);
g->isComplete = 1;
List* vertices = g->verticesList;
ListMoveToHead(vertices);
unsigned int i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
struct _Vertex* v = ListGetCurrentItem(vertices);
List* edges = v->edgesList;
for (unsigned int j = 0; j < g->numVertices; j++) {
if (i == j) {
continue;
}
struct _Edge* new = (struct _Edge*)malloc(sizeof(struct _Edge));
if (new == NULL) abort();
new->adjVertex = j;
new->weight = 1;
ListInsert(edges, new);
}
if (g->isDigraph) {
v->inDegree = g->numVertices - 1;
v->outDegree = g->numVertices - 1;
} else {
v->outDegree = g->numVertices - 1;
}
}
if (g->isDigraph) {
g->numEdges = numVertices * (numVertices - 1);
} else {
g->numEdges = numVertices * (numVertices - 1) / 2;
}
return g;
}
// Create the transpose of a directed graph
// This function should never be called on an undirected graph
// This function should never be called on a complete graph
Graph* GraphCreateTranspose(const Graph* g) {
assert(g != NULL);
assert(g->isDigraph);
assert(g->isComplete == 0);
// COMPLETE THE CODE
Graph* transposto = GraphCreate(g->numVertices, 1, g->isWeighted); // Inicia um grafo onde o transposto irá ser guardado
List* vertices = g->verticesList; // Copia a lista de vertices do grafo original
ListMoveToHead(vertices); // Move o ponteiro para a cabeça da lista
for (unsigned int i = 0; i < g->numVertices; ListMoveToNext(vertices), i++) { // Percorre todos os vertices do grafo original
struct _Vertex* verticeAtual = ListGetCurrentItem(vertices); // Guarda o vertice atual
List* arestas = verticeAtual->edgesList; // Copia a lista de arestas do vertice atual
ListMoveToHead(arestas); // Move o ponteiro para a cabeça da lista
for (unsigned int j = 0; j < verticeAtual->outDegree; ListMoveToNext(arestas), j++) { // Percorre todas as arestas do vertice atual
struct _Edge* arestaAtual = ListGetCurrentItem(arestas); // Guarda a aresta atual
if (g->isWeighted) { // Se o grafo tiver distancias
GraphAddWeightedEdge(transposto, arestaAtual->adjVertex, i, arestaAtual->weight);
} else {
GraphAddEdge(transposto, arestaAtual->adjVertex, i);
}
}
}
return transposto;
}
void GraphDestroy(Graph** p) {
assert(*p != NULL);
Graph* g = *p;
List* vertices = g->verticesList;
if (ListIsEmpty(vertices) == 0) {
ListMoveToHead(vertices);
unsigned int i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
struct _Vertex* v = ListGetCurrentItem(vertices);
List* edges = v->edgesList;
if (ListIsEmpty(edges) == 0) {
int i = 0;
ListMoveToHead(edges);
for (; i < ListGetSize(edges); ListMoveToNext(edges), i++) {
struct _Edge* e = ListGetCurrentItem(edges);
free(e);
}
}
ListDestroy(&(v->edgesList));
free(v);
}
}
ListDestroy(&(g->verticesList));
free(g);
*p = NULL;
}
// Read a graph from file
// Using the simple graph format of Sedgewick and Wayne
// Input argument must be a valid FILE POINTER
// File must be openend and closed by the caller
Graph* GraphFromFile(FILE* f) {
assert(f != NULL);
unsigned int isDigraph;
fscanf(f, "%u", &isDigraph);
unsigned int isWeighted;
fscanf(f, "%u", &isWeighted);
unsigned int numVertices;
fscanf(f, "%u", &numVertices);
unsigned int numEdges;
fscanf(f, "%u", &numEdges);
Graph* g = GraphCreate(numVertices, isDigraph, isWeighted);
// Read the edges and add them to the graph
unsigned int start_vertex;
unsigned int end_vertex;
double weight;
if (isWeighted == 0) {
for (unsigned int i = 0; i < numEdges; i++) {
fscanf(f, "%u", &start_vertex);
fscanf(f, "%u", &end_vertex);
GraphAddEdge(g, start_vertex, end_vertex);
}
} else {
for (unsigned int i = 0; i < numEdges; i++) {
fscanf(f, "%u", &start_vertex);
fscanf(f, "%u", &end_vertex);
fscanf(f, "%lf", &weight);
GraphAddWeightedEdge(g, start_vertex, end_vertex, weight);
}
}
assert(numEdges == g->numEdges);
return g;
}
// Graph
int GraphIsDigraph(const Graph* g) { return g->isDigraph; }
int GraphIsComplete(const Graph* g) { return g->isComplete; }
int GraphIsWeighted(const Graph* g) { return g->isWeighted; }
unsigned int GraphGetNumVertices(const Graph* g) { return g->numVertices; }
unsigned int GraphGetNumEdges(const Graph* g) { return g->numEdges; }
//
// For a graph
//
double GraphGetAverageDegree(const Graph* g) {
assert(g->isDigraph == 0);
return 2.0 * (double)g->numEdges / (double)g->numVertices;
}
static unsigned int _GetMaxDegree(const Graph* g) {
List* vertices = g->verticesList;
if (ListIsEmpty(vertices)) return 0;
unsigned int maxDegree = 0;
ListMoveToHead(vertices);
unsigned int i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
struct _Vertex* v = ListGetCurrentItem(vertices);
if (v->outDegree > maxDegree) {
maxDegree = v->outDegree;
}
}
return maxDegree;
}
//
// For a graph
//
unsigned int GraphGetMaxDegree(const Graph* g) {
assert(g->isDigraph == 0);
return _GetMaxDegree(g);
}
//
// For a digraph
//
unsigned int GraphGetMaxOutDegree(const Graph* g) {
assert(g->isDigraph == 1);
return _GetMaxDegree(g);
}
// Vertices
//
// returns an array of size (outDegree + 1)
// element 0, stores the number of adjacent vertices
// and is followed by indices of the adjacent vertices
//
unsigned int* GraphGetAdjacentsTo(const Graph* g, unsigned int v) {
assert(v < g->numVertices);
// Node in the list of vertices
List* vertices = g->verticesList;
ListMove(vertices, v);
struct _Vertex* vPointer = ListGetCurrentItem(vertices);
unsigned int numAdjVertices = vPointer->outDegree;
unsigned int* adjacent =
(unsigned int*)calloc(1 + numAdjVertices, sizeof(unsigned int));
if (numAdjVertices > 0) {
adjacent[0] = numAdjVertices;
List* adjList = vPointer->edgesList;
ListMoveToHead(adjList);
for (unsigned int i = 0; i < numAdjVertices; ListMoveToNext(adjList), i++) {
struct _Edge* ePointer = ListGetCurrentItem(adjList);
adjacent[i + 1] = ePointer->adjVertex;
}
}
return adjacent;
}
//
// returns an array of size (outDegree + 1)
// element 0, stores the number of adjacent vertices
// and is followed by the distances to the adjacent vertices
//
double* GraphGetDistancesToAdjacents(const Graph* g, unsigned int v) {
assert(v < g->numVertices);
// Node in the list of vertices
List* vertices = g->verticesList;
ListMove(vertices, v);
struct _Vertex* vPointer = ListGetCurrentItem(vertices);
unsigned int numAdjVertices = vPointer->outDegree;
double* distance = (double*)calloc(1 + numAdjVertices, sizeof(double));
if (numAdjVertices > 0) {
distance[0] = numAdjVertices;
List* adjList = vPointer->edgesList;
ListMoveToHead(adjList);
for (unsigned int i = 0; i < numAdjVertices; ListMoveToNext(adjList), i++) {
struct _Edge* ePointer = ListGetCurrentItem(adjList);
distance[i + 1] = ePointer->weight;
}
}
return distance;
}
//
// For a graph
//
unsigned int GraphGetVertexDegree(Graph* g, unsigned int v) {
assert(g->isDigraph == 0);
assert(v < g->numVertices);
ListMove(g->verticesList, v);
struct _Vertex* p = ListGetCurrentItem(g->verticesList);
return p->outDegree;
}
//
// For a digraph
//
unsigned int GraphGetVertexOutDegree(Graph* g, unsigned int v) {
assert(g->isDigraph == 1);
assert(v < g->numVertices);
ListMove(g->verticesList, v);
struct _Vertex* p = ListGetCurrentItem(g->verticesList);
return p->outDegree;
}
//
// For a digraph
//
unsigned int GraphGetVertexInDegree(Graph* g, unsigned int v) {
assert(g->isDigraph == 1);
assert(v < g->numVertices);
ListMove(g->verticesList, v);
struct _Vertex* p = ListGetCurrentItem(g->verticesList);
return p->inDegree;
}
// Edges
static int _addEdge(Graph* g, unsigned int v, unsigned int w, double weight) {
// Insert edge (v,w)
struct _Edge* edge_v_w = (struct _Edge*)malloc(sizeof(struct _Edge));
edge_v_w->adjVertex = w;
edge_v_w->weight = weight;
ListMove(g->verticesList, v);
struct _Vertex* vertex_v = ListGetCurrentItem(g->verticesList);
int result = ListInsert(vertex_v->edgesList, edge_v_w);
if (result == -1) {
// Insertion failed --- Destroy the allocated edge
free(edge_v_w);
return 0;
}
// Update
g->numEdges++;
vertex_v->outDegree++;
ListMove(g->verticesList, w);
struct _Vertex* vertex_w = ListGetCurrentItem(g->verticesList);
// DIRECTED GRAPH --- Update the in-degree of vertex w
if (g->isDigraph == 1) {
vertex_w->inDegree++;
}
// If UNDIRECTED GRAPH
if (g->isDigraph == 0) {
// It is a BIDIRECTIONAL EDGE --- Insert edge (w,v)
struct _Edge* edge_w_v = (struct _Edge*)malloc(sizeof(struct _Edge));
edge_w_v->adjVertex = v;
edge_w_v->weight = weight;
result = ListInsert(vertex_w->edgesList, edge_w_v);
if (result == -1) {
// Insertion failed --- Destroy the allocated edge
free(edge_w_v);
// And remove the edge (v,w) that was inserted above
ListSearch(vertex_v->edgesList, (void*)edge_v_w);
ListRemoveCurrent(vertex_v->edgesList);
// UNDO the updates
g->numEdges--;
vertex_v->outDegree--;
vertex_w->inDegree--;
return 0;
} else {
// g->numEdges++; // Do not count the same edge twice on a undirected
// graph !!
// Just update the outDegree of vertex w
vertex_w->outDegree++;
}
}
return 1;
}
int GraphAddEdge(Graph* g, unsigned int v, unsigned int w) {
assert(g->isWeighted == 0);
assert(v != w);
assert(v < g->numVertices);
assert(w < g->numVertices);
return _addEdge(g, v, w, 1.0);
}
int GraphAddWeightedEdge(Graph* g, unsigned int v, unsigned int w,
double weight) {
assert(g->isWeighted == 1);
assert(v != w);
assert(v < g->numVertices);
assert(w < g->numVertices);
return _addEdge(g, v, w, weight);
}
// CHECKING
int GraphCheckInvariants(const Graph* g) {
assert(g != NULL);
assert(g->isComplete == 0 || g->isComplete == 1);
assert(g->isDigraph == 0 || g->isDigraph == 1);
assert(g->isWeighted == 0 || g->isWeighted == 1);
if (g->isComplete) {
unsigned int n = g->numVertices;
if (g->isDigraph) {
assert(g->numEdges == n * (n - 1));
} else {
assert(g->numEdges == n * (n - 1) / 2);
}
}
// Checking the vertices list
ListTestInvariants(g->verticesList);
assert((int)g->numVertices == ListGetSize(g->verticesList));
// Checking the total number of edges
unsigned int out_degree_total = 0;
unsigned int in_degree_total = 0;
List* vertices = g->verticesList;
ListMoveToHead(vertices);
unsigned int i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
struct _Vertex* v = ListGetCurrentItem(vertices);
out_degree_total += v->outDegree;
if (g->isDigraph) {
in_degree_total += v->inDegree;
}
}
if (g->isDigraph) {
assert(in_degree_total == out_degree_total);
assert(g->numEdges == out_degree_total);
} else {
// Unidrected graph
assert(g->numEdges == out_degree_total / 2);
}
// For each vertex, checking its adjacency list
ListMoveToHead(vertices);
i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
struct _Vertex* v = ListGetCurrentItem(vertices);
List* edges = v->edgesList;
ListTestInvariants(edges);
assert((int)v->outDegree == ListGetSize(edges));
}
return 0;
}
// DISPLAYING on the console
void GraphDisplay(const Graph* g) {
printf("---\n");
if (g->isWeighted) {
printf("Weighted ");
}
if (g->isComplete) {
printf("COMPLETE ");
}
if (g->isDigraph) {
printf("Digraph\n");
printf("Max Out-Degree = %d\n", GraphGetMaxOutDegree(g));
} else {
printf("Graph\n");
printf("Max Degree = %d\n", GraphGetMaxDegree(g));
}
printf("Vertices = %2d | Edges = %2d\n", g->numVertices, g->numEdges);
List* vertices = g->verticesList;
ListMoveToHead(vertices);
unsigned int i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
printf("%2d ->", i);
struct _Vertex* v = ListGetCurrentItem(vertices);
if (ListIsEmpty(v->edgesList)) {
printf("\n");
} else {
List* edges = v->edgesList;
int i = 0;
ListMoveToHead(edges);
for (; i < ListGetSize(edges); ListMoveToNext(edges), i++) {
struct _Edge* e = ListGetCurrentItem(edges);
if (g->isWeighted) {
printf(" %2d(%4.2f)", e->adjVertex, e->weight);
} else {
printf(" %2d", e->adjVertex);
}
}
printf("\n");
// Checking the invariants of the list of edges
ListTestInvariants(edges);
}
}
printf("---\n");
// Checking the invariants of the list of vertices
ListTestInvariants(vertices);
}
void GraphListAdjacents(const Graph* g, unsigned int v) {
printf("---\n");
unsigned int* array = GraphGetAdjacentsTo(g, v);
printf("Vertex %d has %d adjacent vertices -> ", v, array[0]);
for (unsigned int i = 1; i <= array[0]; i++) {
printf("%d ", array[i]);
}
printf("\n");
free(array);
printf("---\n");
}
// Display the graph in DOT language.
// To draw the graph, you can use dot (from Graphviz) or paste result on:
// https://dreampuf.github.io/GraphvizOnline
void GraphDisplayDOT(const Graph* g) {
char* gtypes[] = {"graph", "digraph"};
char* edgeops[] = {"--", "->"};
char* gtype = gtypes[g->isDigraph];
char* edgeop = edgeops[g->isDigraph];
printf("// Paste in: https://dreampuf.github.io/GraphvizOnline\n");
printf("%s {\n", gtype);
printf(" // Vertices = %2d\n", g->numVertices);
printf(" // Edges = %2d\n", g->numEdges);
if (g->isDigraph) {
printf(" // Max Out-Degree = %d\n", GraphGetMaxOutDegree(g));
} else {
printf(" // Max Degree = %d\n", GraphGetMaxDegree(g));
}
List* vertices = g->verticesList;
ListMoveToHead(vertices);
unsigned int i = 0;
for (; i < g->numVertices; ListMoveToNext(vertices), i++) {
printf(" %d;\n", i);
struct _Vertex* v = ListGetCurrentItem(vertices);
List* edges = v->edgesList;
int k = 0;
ListMoveToHead(edges);
for (; k < ListGetSize(edges); ListMoveToNext(edges), k++) {
struct _Edge* e = ListGetCurrentItem(edges);
unsigned int j = e->adjVertex;
if (g->isDigraph || i <= j) { // for graphs, draw only 1 edge
printf(" %d %s %d", i, edgeop, j);
if (g->isWeighted) {
printf(" [label=%4.2f]", e->weight);
}
printf(";\n");
}
}
}
printf("}\n");
}