-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.c
More file actions
93 lines (76 loc) · 2 KB
/
Graph.c
File metadata and controls
93 lines (76 loc) · 2 KB
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
//
// Graph.c
// Assignment2
//
// Created by JIHUI LIANG on 21/1/19.
// Copyright © 2019 JIHUI LIANG. All rights reserved.
//
// Graph ADT
#include "Graph.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct GraphRep {
int **edges; // adjacency matrix
int nV; // #vertices
int nE; // #edges
} GraphRep;
Graph newGraph(int V) {
assert(V >= 0);
int i;
Graph g = malloc(sizeof(GraphRep));
assert(g != NULL);
g->nV = V;
g->nE = 0;
// allocate memory for each row
g->edges = malloc(V * sizeof(int *));
assert(g->edges != NULL);
// allocate memory for each column and initialise with 0
for (i = 0; i < V; i++) {
g->edges[i] = calloc(V, sizeof(int));
assert(g->edges[i] != NULL);
}
return g;
}
// check if vertex is valid in a graph
bool validV(Graph g, Vertex v) {
return (g != NULL && v >= 0 && v < g->nV);
}
void insertEdge(Graph g, Edge e) {
assert(g != NULL && validV(g,e.v) && validV(g,e.w));
if (!g->edges[e.v][e.w]) { // edge e not in graph
g->edges[e.v][e.w] = 1;
//g->edges[e.w][e.v] = 1;
g->nE++;
}
}
void removeEdge(Graph g, Edge e) {
assert(g != NULL && validV(g,e.v) && validV(g,e.w));
if (g->edges[e.v][e.w]) { // edge e in graph
g->edges[e.v][e.w] = 0;
g->edges[e.w][e.v] = 0;
g->nE--;
}
}
bool adjacent(Graph g, Vertex v, Vertex w) {
assert(g != NULL && validV(g,v) && validV(g,w));
return (g->edges[v][w] != 0);
}
void showGraph(Graph g) {
assert(g != NULL);
int i, j;
printf("Number of vertices: %d\n", g->nV);
printf("Number of edges: %d\n", g->nE);
for (i = 0; i < g->nV; i++)
for (j = i+1; j < g->nV; j++)
if (g->edges[i][j])
printf("Edge %d - %d\n", i, j);
}
void freeGraph(Graph g) {
assert(g != NULL);
int i;
for (i = 0; i < g->nV; i++)
free(g->edges[i]);
free(g->edges);
free(g);
}