-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.c
75 lines (64 loc) · 1.61 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "graph.h"
graph *createGraph(int vertices)
{
graph *graph = malloc(sizeof(struct Graph));
if (graph == NULL)
{
perror("Graph Not Initialized");
return NULL;
}
// Init graph properties
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(node *));
graph->visited = malloc(vertices * sizeof(int));
for (int i = 0; i < vertices; i++)
{
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
node *createNode(int vertex)
{
node *newNode = malloc(sizeof(node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;
}
void addEdge(graph *graph, int src, int dest)
{
// Add edge from src to dest
node *newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
/*newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;*/
}
void printGraph(graph *graph)
{
int MAX = 30;
int maxPrint = graph->numVertices > MAX ? MAX : graph->numVertices;
for (int i = 0; i <= maxPrint; i++)
{
if (graph->adjLists[i] == NULL)
{
continue;
}
node *pointer = graph->adjLists[i];
printf("%i: ", i);
while (pointer != NULL)
{
if (pointer != NULL)
{
printf("%d ", pointer->vertex);
pointer = pointer->next;
}
}
printf("\n");
}
}