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:

  1. The code starts by including the necessary libraries iostream and vector for input/output and vector operations respectively.

  2. The Graph class is defined to represent the directed graph. It has two private members: V to store the number of vertices and adj to store the adjacency list.

  3. The constructor Graph(int V) initializes the number of vertices and resizes the adjacency list to accommodate the vertices.

  4. The addEdge(int src, int dest) function is used to add an edge from source vertex src to destination vertex dest. It adds dest to the adjacency list of src.

  5. The printGraph() function is used to print the adjacency list representation of the graph. It iterates over each vertex and prints its adjacency list.

  6. In the main() function, an instance of the Graph class g is created with 5 vertices.

  7. Edges are added to the graph using the addEdge() function. This creates a directed edge from one vertex to another.

  8. Finally, the printGraph() function is called to display the adjacency list representation of the graph.

  9. The program ends with a return 0; statement.

I hope this example helps! Let me know if you have any further questions.