-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.h
456 lines (391 loc) · 10.4 KB
/
graph.h
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
/**
\file graph.h
\author Brennan Cathcart <brennancathcart@gmail.com>
*/
#ifndef GRAPH_H
#define GRAPH_H
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
// Classes
template <class T>
class Edge;
template <class T>
class Vertex;
template <class T>
class Graph;
/*** EDGE ***/
template <class T>
class Edge
{
public:
Edge(const T dest, const double weight, const T* id = nullptr);
void setWeight(const double weight);
const double weight() const;
const T dest() const;
const T id() const;
private:
T dest_;
double weight_;
T id_; // Optional identifier
};
template <class T>
Edge<T>::Edge(const T dest, const double weight, const T* id)
: dest_(dest),
weight_(weight)
{
if (id != nullptr)
id_ = *id;
}
template <class T>
void Edge<T>::setWeight(const double weight)
{
weight_ = weight;
}
template <class T>
const double Edge<T>::weight() const
{
return weight_;
}
template <class T>
const T Edge<T>::dest() const
{
return dest_;
}
template <class T>
const T Edge<T>::id() const
{
return id_;
}
/*** VERTEX ***/
template <class T>
class Vertex
{
public:
~Vertex();
bool addEdge(const T dest, const double weight, const T* id = nullptr);
bool updateEdgeWeight(const T dest, const double weight) const;
bool removeEdge(const T dest);
const double weight(const T dest) const;
const vector<Edge<T>* > edgeList() const;
private:
vector<Edge<T>* > edges_;
Edge<T>* getEdge(const T dest) const;
};
template <class T>
Vertex<T>::~Vertex()
{
for (const Edge<T>* edge : edges_)
{
delete edge;
}
}
template <class T>
bool Vertex<T>::addEdge(const T dest, const double weight, const T* id)
{
if (!getEdge(dest))
{
edges_.push_back(new Edge<T>(dest, weight, id));
return true;
}
else
{
return false;
}
}
template <class T>
bool Vertex<T>::updateEdgeWeight(const T dest, const double weight) const
{
Edge<T>* edge = getEdge(dest);
if (edge)
{
edge->setWeight(weight);
return true;
}
else
{
return false;
}
}
template <class T>
bool Vertex<T>::removeEdge(const T dest)
{
for (class vector<Edge<T>* >::iterator it = edges_.begin(); it != edges_.end(); it++)
{
if ((*it)->dest() == dest)
{
edges_.erase(it);
return true;
}
}
return false;
}
template <class T>
const double Vertex<T>::weight(const T dest) const
{
const Edge<T>* edge = getEdge(dest);
if (edge)
{
return edge->weight();
}
else
{
return std::numeric_limits<double>::infinity();
}
}
template <class T>
const vector<Edge<T>* > Vertex<T>::edgeList() const
{
return edges_;
}
template <class T>
Edge<T>* Vertex<T>::getEdge(const T dest) const
{
for (Edge<T>* edge : edges_)
{
if (edge->dest() == dest)
{
return edge;
}
}
return nullptr;
}
/*** GRAPH ***/
template <class T>
class Graph
{
public:
Graph();
Graph(bool use_edge_id);
~Graph();
bool addVertex(const T id);
bool removeVertex(const T id);
bool addEdge(const T src, const T dest, const double weight, const T* id = nullptr);
bool removeEdge(const T src, const T dest);
bool updateEdgeWeight(const T src, const T dest, const double weight);
const vector<T> bestPath(const T src, const T dest) const;
void print() const;
private:
map<const T, Vertex<T>* > vertices_;
bool use_edge_id_;
};
template <class T>
Graph<T>::Graph()
: use_edge_id_(false) {}
template <class T>
Graph<T>::Graph(bool use_edge_id)
: use_edge_id_(use_edge_id) {}
template <class T>
Graph<T>::~Graph()
{
for (auto const &pair : vertices_)
{
delete pair.second;
}
}
template <class T>
bool Graph<T>::addVertex(const T id)
{
if (vertices_.count(id))
{
cerr << "warning: cannot add vertex: vertex already exists" << endl;
return false;
}
vertices_[id] = new Vertex<T>();
return true;
}
template <class T>
bool Graph<T>::removeVertex(const T id)
{
class map<const T, Vertex<T>* >::iterator vertex_it = vertices_.find(id);
if (vertex_it == vertices_.end())
{
cerr << "warning: cannot remove vertex: vertex doesn't exists" << endl;
return false;
}
Vertex<T>* vertex = vertex_it->second;
vertices_.erase(vertex_it);
// Remove all incoming edges
for (auto const &pair : vertices_)
{
pair.second->removeEdge(id);
}
delete vertex;
return true;
}
template <class T>
bool Graph<T>::addEdge(const T src, const T dest, const double weight, const T* id)
{
if (src == dest)
{
cerr << "error: cannot add edge: source and destination vertices are the same." << endl;
return false;
}
if (use_edge_id_ && id == nullptr)
{
cerr << "error: cannot add edge: edge ID expected." << endl;
return false;
}
class map<const T, Vertex<T>* >::iterator src_it = vertices_.find(src);
// Add vertices if they don't exist
if (src_it == vertices_.end())
{
cout << "note: source vertex doesn't exist: adding " << src << endl;
this->addVertex(src);
src_it = vertices_.find(src);
}
if (!vertices_.count(dest))
{
cout << "note: destination vertex doesn't exist: adding " << dest << endl;
this->addVertex(dest);
}
if (!src_it->second->addEdge(dest, weight, id))
{
cerr << "warning: cannot add edge: edge already exists" << endl;
return false;
}
return true;
}
template <class T>
bool Graph<T>::updateEdgeWeight(const T src, const T dest, const double weight)
{
if (src == dest)
{
cerr << "warning: cannot update edge wight: source and destination vertices are the same" << endl;
return false;
}
class map<const T, Vertex<T>* >::iterator src_it = vertices_.find(src);
if (src_it == vertices_.end())
{
cerr << "warning: cannot update edge weight: source vertex doesn't exist" << endl;
}
if (!vertices_.count(dest))
{
cerr << "warning: cannot update edge weight: destination vertex doesn't exist" << endl;
}
if (!src_it->second->updateEdgeWeight(dest, weight))
{
cerr << "warning: cannot update edge weight: edge doesn't exist" << endl;
return false;
}
return true;
}
template <class T>
bool Graph<T>::removeEdge(const T src, const T dest)
{
class map<const T, Vertex<T>* >::iterator src_it = vertices_.find(src);
if (src_it == vertices_.end() || !vertices_.count(dest))
{
cerr << "error: cannot remove edge: source or destination vertex doesn't exist" << endl;
return false;
}
int success = src_it->second->removeEdge(dest);
if (!success)
{
cerr << "error: cannot remove edge: edge doesn't exists" << endl;
}
return success;
}
// Time complexity: O(ElogV)
template <class T>
const vector<T> Graph<T>::bestPath(const T src, const T dest) const
{
if (!vertices_.count(src) || !vertices_.count(dest))
{
throw std::invalid_argument("cannot find best path because source and/or destination vertices don't exist");
}
/* Apply Dijkstra's shortest path algorithm to the graph */
map<const T, double> dist; // Maps a vertex to its distance from src
map<const T, T> previous_vertex; // Maps a vertex to the previous vertex along the best path
map<const T, T> previous_edge; // Maps a vertex to the incoming edge along the best path
for (auto const &pair : vertices_)
{
dist[pair.first] = std::numeric_limits<double>::infinity();
}
dist[src] = 0.0f;
// Initialize priority queue with source vertex
priority_queue<pair<double, T>, vector<pair<double, T> >, greater<pair<double, T> > > vertices_queue;
vertices_queue.push(pair<double, T>(0, src));
while (!vertices_queue.empty())
{
// Get the vertex with the smallest distance from src
pair<double, T> smallest_pair = vertices_queue.top();
double dist_to_vertex = smallest_pair.first;
const T vertex = smallest_pair.second;
vertices_queue.pop();
// Stop searching if reached the dest vertex
if (vertex == dest) {
break;
}
// Check if there are now shorter distances to each neighbour
const vector<Edge<T>* > edge_list = vertices_.find(vertex)->second->edgeList();
for (const Edge<T>* edge : edge_list)
{
double new_dist = dist_to_vertex + edge->weight();
const T edge_dest = edge->dest();
if (new_dist < dist[edge_dest])
{
// Note: We may push duplicate vertices to the priority queue but this is expected
vertices_queue.push(pair<double, T>(new_dist, edge_dest));
dist[edge_dest] = new_dist;
previous_vertex[edge_dest] = vertex;
if (use_edge_id_)
{
previous_edge[edge_dest] = edge->id();
}
}
}
}
// Return an empty vector if dest vertex is not reachable from src vertex
if (dist[dest] == std::numeric_limits<double>::infinity())
{
return vector<T>();
}
/* Get the best path */
vector<T> path;
T vertex_id = dest;
if (use_edge_id_)
{
// Populate path with edge IDs along best path
while (vertex_id != src)
{
path.push_back(previous_edge[vertex_id]);
vertex_id = previous_vertex[vertex_id];
}
}
else
{
// Populate path vith vertex IDs along best path
path.push_back(dest);
while (vertex_id != src)
{
path.push_back(previous_vertex[vertex_id]);
vertex_id = previous_vertex[vertex_id];
}
}
std::reverse(path.begin(), path.end());
return path;
}
template <class T>
void Graph<T>::print() const
{
cout << "Graph:" << endl;
for (auto const &pair : vertices_)
{
cout << pair.first << ": ";
const vector<Edge<T>* > edges = pair.second->edgeList();
for (class vector<Edge<T>* >::const_iterator it = edges.begin(); it != edges.end(); it++)
{
cout << "[" << (*it)->dest() << ":" << (*it)->weight() << "]";
if (it != edges.end() - 1)
{
cout << ", ";
}
}
cout << endl;
}
}
#endif // GRAPH_H