-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedGraphImplementation.cpp
More file actions
59 lines (49 loc) · 1.05 KB
/
DirectedGraphImplementation.cpp
File metadata and controls
59 lines (49 loc) · 1.05 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
#include <iostream>
#include <vector>
struct Edge
{
int src;
int dest;
};
class DirectedGraph
{
private:
int nodes;
std::vector<std::vector<int>> adjlist;
public:
DirectedGraph(int numnodes, const std::vector<Edge>& edges)
: nodes(numnodes)
{
// With std::vector::reserve, you only allocate the specified amount
// of memory. The logical size of the vector is still the same. So,
// you need to push back elements
// With std::vector::resize, the size of the vector is modified. So,
// you can directly index into elements
adjlist.resize(numnodes);
for (auto iter : edges)
{
adjlist[iter.src].push_back(iter.dest);
}
}
void print()
{
std::cout << "Directed graph" << std::endl;
for (int i = 0; i < nodes; ++i)
{
std::cout << "(" << i;
for (auto j : adjlist[i])
{
std::cout << " ," << j;
}
std::cout << ")" << std::endl;
}
}
};
int main()
{
std::vector<Edge> edges{ {0, 1}, {1, 2}, {2, 0}, {2, 1}, {3, 2}, {4, 5}, {5, 4} };
int numnodes = 6;
DirectedGraph obj(numnodes, edges);
obj.print();
return 0;
}