-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgraph.cpp
More file actions
127 lines (99 loc) · 2.77 KB
/
Copy pathgraph.cpp
File metadata and controls
127 lines (99 loc) · 2.77 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
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
#include <iostream>
using namespace std;
// Data structure to store adjacency list nodes
struct Node
{
int val;
Node* next;
};
// Data structure to store a graph edge
struct Edge {
int src, dest;
};
class Graph
{
// Function to allocate a new node for the adjacency list
Node* getAdjListNode(int dest, Node* head)
{
Node* newNode = new Node;
newNode->val = dest;
// point new node to the current head
newNode->next = head;
return newNode;
}
int N; // total number of nodes in the graph
public:
// An array of pointers to Node to represent the
// adjacency list
Node **head;
// Constructor
Graph(Edge edges[], int n, int N)
{
// allocate memory
head = new Node*[N]();
this->N = N;
// initialize head pointer for all vertices
for (int i = 0; i < N; i++) {
head[i] = nullptr;
}
// add edges to the directed graph
for (unsigned i = 0; i < n; i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
// insert at the beginning
Node* newNode = getAdjListNode(dest, head[src]);
// point head pointer to the new node
head[src] = newNode;
// uncomment the following code for undirected graph
/*
newNode = getAdjListNode(src, head[dest]);
// change head pointer to point to the new node
head[dest] = newNode;
*/
}
}
// Destructor
~Graph() {
for (int i = 0; i < N; i++) {
delete[] head[i];
}
delete[] head;
}
};
// Function to print all neighboring vertices of a given vertex
void printList(Node* ptr)
{
while (ptr != nullptr)
{
cout << " —> " << ptr->val << " ";
ptr = ptr->next;
}
cout << endl;
}
// Graph implementation in C++ without using STL
int main()
{
// an array of graph edges as per the above diagram
Edge edges[] =
{
// pair `(x, y)` represents an edge from `x` to `y`
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 },
{ 3, 2 }, { 4, 5 }, { 5, 4 }
};
// total number of nodes in the graph
int N = 6;
// calculate the total number of edges
int n = sizeof(edges)/sizeof(edges[0]);
// construct graph
Graph graph(edges, n, N);
// print adjacency list representation of a graph
for (int i = 0; i < N; i++)
{
// print given vertex
cout << i << " ——";
// print all its neighboring vertices
printList(graph.head[i]);
}
return 0;
}