directed graph in cpp
Sure! Here is an example of how to implement a directed graph in C++:
#include <iostream>
#include <vector>
using namespace std;
class Graph {
int V; // number of vertices
vector<vector<int>> adj; // adjacency list
public:
Graph(int V) {
this->V = V;
adj.resize(V);
}
// function to add an edge to the graph
void addEdge(int src, int dest) {
adj[src].push_back(dest);
}
// function to print the graph
void printGraph() {
for (int i = 0; i < V; ++i) {
cout << "Adjacency list of vertex " << i << ": ";
for (const auto& j : adj[i]) {
cout << j << " ";
}
cout << endl;
}
}
};
int main() {
// create a graph with 5 vertices
Graph g(5);
// add edges to the graph
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
// print the graph
g.printGraph();
return 0;
}
Explanation of each step:
The code starts by including the necessary libraries
iostream
andvector
for input/output and vector operations respectively.The
Graph
class is defined to represent the directed graph. It has two private members:V
to store the number of vertices andadj
to store the adjacency list.The constructor
Graph(int V)
initializes the number of vertices and resizes the adjacency list to accommodate the vertices.The
addEdge(int src, int dest)
function is used to add an edge from source vertexsrc
to destination vertexdest
. It addsdest
to the adjacency list ofsrc
.The
printGraph()
function is used to print the adjacency list representation of the graph. It iterates over each vertex and prints its adjacency list.In the
main()
function, an instance of theGraph
classg
is created with 5 vertices.Edges are added to the graph using the
addEdge()
function. This creates a directed edge from one vertex to another.Finally, the
printGraph()
function is called to display the adjacency list representation of the graph.The program ends with a
return 0;
statement.
I hope this example helps! Let me know if you have any further questions.