Skip to content

Commit 384c6d4

Browse files
authored
Create 04 - Adjacency List - Vector.cpp
1 parent 0daa8cb commit 384c6d4

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// Graph Class Definition
6+
class Graph {
7+
public:
8+
// Adjacency List represented using a vector of vectors
9+
vector<vector<int>> adjacencyList;
10+
11+
// Constructor to initialize the adjacency list with the given number of nodes
12+
Graph(int totalNodes) {
13+
adjacencyList.resize(totalNodes); // Resize the vector to hold 'totalNodes' vectors
14+
}
15+
16+
// Function to add an edge to the graph
17+
void addEdge(int sourceNode, int destinationNode, bool isDirected = false) {
18+
// Add the edge from source to destination
19+
adjacencyList[sourceNode].push_back(destinationNode);
20+
21+
// If the graph is undirected, add the reverse edge
22+
if (!isDirected) {
23+
adjacencyList[destinationNode].push_back(sourceNode);
24+
}
25+
}
26+
27+
// Function to print the adjacency list
28+
void printGraph() {
29+
for (int node = 0; node < adjacencyList.size(); node++) {
30+
cout << node << " -> ";
31+
for (int neighbor : adjacencyList[node]) {
32+
cout << neighbor << ", ";
33+
}
34+
cout << endl;
35+
}
36+
}
37+
};
38+
39+
int main() {
40+
int numberOfNodes;
41+
cout << "Enter the number of nodes in the graph:" << endl;
42+
cin >> numberOfNodes;
43+
44+
int numberOfEdges;
45+
cout << "Enter the number of edges in the graph:" << endl;
46+
cin >> numberOfEdges;
47+
48+
// Create a Graph object
49+
Graph graphInstance(numberOfNodes);
50+
51+
// Input edges
52+
cout << "Enter the edges (sourceNode destinationNode):" << endl;
53+
for (int i = 0; i < numberOfEdges; i++) {
54+
int sourceNode, destinationNode;
55+
cin >> sourceNode >> destinationNode;
56+
57+
// Add the edge to the graph (default: undirected)
58+
graphInstance.addEdge(sourceNode, destinationNode, false);
59+
}
60+
61+
// Print the graph representation
62+
cout << "Adjacency List of the graph:" << endl;
63+
graphInstance.printGraph();
64+
65+
return 0;
66+
}

0 commit comments

Comments
 (0)