1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include "graph.h"
5
6 static void _make_peer(HeadNode * head, int peerVertex, int weight);
7
8 static void _dfs(Graph * g, int from,bool * visited);
9
10 static void _make_peer(HeadNode * head, int peerVertex, int weight)
11 {
12 PeerNode * newPeer = (PeerNode *)malloc(sizeof(PeerNode));
13 newPeer->peer = peerVertex;
14 newPeer->weight = weight;
15 newPeer->next = head->firstPeer;
16 head->firstPeer = newPeer;
17 }
18
19 void create_graph(Graph * g, int vertexSize)
20 {
21 g->vertexSize = vertexSize;
22 g->vertex = (int *)malloc(sizeof(int) * vertexSize);
23 g->head = (HeadNode *)malloc(sizeof(HeadNode) * vertexSize);
24 for(int i = 0; i < vertexSize; i++)
25 {
26 g->vertex[i] = 0;
27 g->head[i].vertex = i;
28 g->head[i].adjSize = 0;
29 g->head[i].firstPeer = NULL;
30 }
31 }
32
33 void destroy_graph(Graph * g)
34 {
35 for(int i = 0; i < g->vertexSize; i++)
36 {
37 PeerNode * current = g->head[i].firstPeer;
38 PeerNode * nextNode = NULL;
39 while(current)
40 {
41 nextNode = current->next;
42 free(current);
43 current = nextNode;
44 }
45 }
46 free(g->head);
47 free(g->vertex);
48 }
49
50 bool make_edge(Graph * g, int from, int to, int weight)
51 {
52 PeerNode * current = g->head[from].firstPeer;
53 while(current)
54 {
55 if(current->peer == to)
56 {
57 printf("(%u, %u) is already exist!
", from, to);
58 return false;
59 }
60 current = current->next;
61 }
62 _make_peer(&g->head[from], to, weight);
63 g->head[from].adjSize++;
64 return true;
65 }
66
67 bool remove_edge(Graph * g, int from, int to)
68 {
69 PeerNode * current = g->head[from].firstPeer;
70 while(current->next && current->next->peer != to)
71 current = current->next;
72 if(!current)
73 {
74 printf("(%d, %d) is not exist!
", from, to);
75 return false;
76 }
77 else
78 {
79 PeerNode * delPeer = current->next;
80 current->next = current->next->next;
81 free(delPeer);
82 return true;
83 }
84 }
85
86 void print_graph(Graph * g)
87 {
88 for(int i = 0; i < g->vertexSize; i++)
89 {
90 HeadNode currentHead = g->head[i];
91 printf("[%d: %d]: ", currentHead.vertex, currentHead.adjSize);
92 PeerNode * currentNode = currentHead.firstPeer;
93 for(;currentNode; currentNode = currentNode->next)
94 printf("(%d, %d) ",currentNode->peer, currentNode->weight);
95 printf("
");
96 }
97 printf("
");
98 }
99
100 //algorithm
101
102 void dfs(Graph * g, int from)
103 {
104 bool * visited = (bool *)malloc(sizeof(bool) * g->vertexSize);
105 memset(visited, 0, g->vertexSize * sizeof(bool));
106 printf("run dfs:
");
107 _dfs(g,from,visited);
108 printf("NULL
");
109 free(visited);
110 }
111
112 static void _dfs(Graph * g, int from,bool * visited)
113 {
114 visited[from] = true;
115 printf("%d - > ", from);
116 PeerNode * currentPeer = g->head[from].firstPeer;
117 while(currentPeer)
118 {
119 int nextFrom = currentPeer->peer;
120 if(!visited[nextFrom])
121 _dfs(g, nextFrom, visited);
122 currentPeer = currentPeer->next;
123 }
124 }