-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDigraph.h
More file actions
97 lines (93 loc) · 2.2 KB
/
Digraph.h
File metadata and controls
97 lines (93 loc) · 2.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
94
95
96
97
#pragma once
#include <vector>
#include <stdexcept>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
// adjacent list representation of an directed graph
class Digraph
{
int vertices;
int edges;
std::vector<int> m_indegree; // vertices indegree
using BagIterator = std::vector<int>::iterator;
using Bag = std::vector<int>;
std::vector<Bag> adjList;
void validateVertex(int v)
{
if (v < 0 || v >= vertices)
{
std::stringstream msg;
msg << "vertex " << v << " is not between 0 and " << (vertices-1);
throw std::out_of_range(msg.str());
}
}
public:
Digraph(int V)
: vertices(V), edges(0), adjList(V), m_indegree(V)
{}
Digraph(const Digraph& g)
: vertices(g.vertices),
edges(g.edges),
adjList(g.adjList),
m_indegree(g.m_indegree)
{}
~Digraph() {}
int V() const { return vertices; }
int E() const { return edges; }
int addEdge(int from, int to)
{
validateVertex(from);
validateVertex(to);
edges++;
adjList[from].push_back(to);
m_indegree[to]++;
}
Bag& adj(int v)
{
validateVertex(v);
return adjList[v];
}
BagIterator begin(int v)
{
validateVertex(v);
return adjList[v].begin();
}
BagIterator end(int v)
{
validateVertex(v);
return adjList[v].end();
}
int indegree(int v)
{
validateVertex(v);
return m_indegree[v];
}
int outdegree(int v)
{
validateVertex(v);
return adjList[v].size();
}
Digraph reverse()
{
Digraph R(vertices);
for (int v = 0; v < vertices; v++)
for (int w : adjList[v])
R.addEdge(w, v);
return R;
}
std::string toString()
{
std::stringstream ss;
ss << vertices << " vertices, " << edges << " edges\n";
for (int v = 0; v < vertices; v++)
{
ss.width(2); ss << v << ": ";
for (int w : adjList[v])
{ ss.width(2); ss << w << " "; }
ss << std::endl;
}
return ss.str();
}
};