Find if there is a path between two vertices in a directed graph



A directed graph is a graph where the edges specify a direction from one vertex to another. In this article, we will learn how to find a path between two vertices in a directed graph and implement C++ code to achieve this. To determine if there is a path between two vertices, there are two common algorithms we can use:

First of all, let's understand what does it meant by having a path between two vertices in a directed graph.

Path Between Two Vertices in Directed Graph

In a directed graph, the path between two vertices refer to a sequence of edges that connects the two vertices, when we move through the direction of the edges. If such a sequence exists, we say that there is a path between the two vertices. To understand the concept better, consider an image of a directed graph below:

Path Between Two Vertices in Directed Graph

Here are the some of the possible paths exists between the vertices of the above graph:

  • Vertex 0 to Vertex 4: Possible Path = 0 -> 2 -> 3 -> 4
  • Vertex 1 to Vertex 4: No path exists
  • Vertex 4 to Vertex 1: Possible Path = 4 -> 2 -> 1
  • Vertex 3 to Vertex 0: No path exists

BFS Algorithm to Find Path Between Two Vertices

To find a path between two vertices in a directed graph, we can use the Breadth First Search (BFS) algorithm. The BFS algorithm is a graph traversal algorithm that visits all the neighbors of the current vertex before moving on to a vertex at the next level. In a directed graph, if we can perform a BFS traversal from a vertex u to a vertex v, it means there is a path from u to v.

Steps to Implement BFS for Path Finding

The steps below shows how to implement the BFS algorithm to find a path between two vertices in a directed graph:

  • Take the input graph in the form of an adjacency list adjList[].
  • Define a queue to keep track of the vertices to be visited and a visited set to keep track of the visited vertices.
  • Create a parent map to reconstruct the path later.
  • Start BFS from the source vertex start.
  • For each vertex, check its neighbors. If a neighbor has not been visited, mark it as visited, add it to the queue, and set its parent.
  • If at any point, start = end it means we have found a path. Reconstruct the path using the parent map.
  • If the queue is empty and without reaching the destination, it means there is no path between the two vertices hence return an empty vector.

C++ Program for BFS Path Finding

Below is a C++ implementation of the BFS algorithm to find a path between two vertices in a directed graph:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;

class DirectedGraph {
    unordered_map<int, vector<int>> adj;

public:
    // Add directed edge from u to v
    void addEdge(int u, int v) {
        adj[u].push_back(v);  // Directed edge
    }

    // BFS to find path from source to destination
    vector<int> bfsPath(int source, int destination) {
        unordered_set<int> visited;
        unordered_map<int, int> parent;
        queue<int> q;

        q.push(source);
        visited.insert(source);
        parent[source] = -1;

        while (!q.empty()) {
            int curr = q.front();
            q.pop();

            if (curr == destination)
                break;

            for (int neighbor : adj[curr]) {
                if (visited.find(neighbor) == visited.end()) {
                    visited.insert(neighbor);
                    parent[neighbor] = curr;
                    q.push(neighbor);
                }
            }
        }

        // Reconstruct path
        vector<int> path;
        if (visited.find(destination) == visited.end())
            return path; // No path found

        for (int at = destination; at != -1; at = parent[at])
            path.push_back(at);

        reverse(path.begin(), path.end());
        return path;
    }
};

int main() {
    DirectedGraph g;

    // Example directed edges
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 3);
    g.addEdge(3, 4);
    g.addEdge(5, 6); // disconnected component

    int source = 0, destination = 4;

    vector<int> path = g.bfsPath(source, destination);

    if (!path.empty()) {
        cout << "Path from " << source << " to " << destination << ": ";
        for (int node : path)
            cout << node << " ";
        cout << endl;
    } else {
        cout << "No path found from " << source << " to " << destination << endl;
    }

    return 0;
}

The output of above code will be:

Path from 0 to 4: 0 2 3 4

DFS Algorithm to Find Path Between Two Vertices

The DFS algorithm is a graph traversal algorithm that visits all the depths of a vertex before backtracking and moving to the next vertex. If we can perform a DFS traversal from a vertex u to a vertex v, it means there is a path from u to v.

Steps to Implement DFS for Path Finding

The steps below shows how to implement the DFS algorithm to find a path between two vertices in a directed graph:

  • Initialize a vector path to store the path from source to destination and a set visited to keep track of visited nodes.
  • Define a recursive function dfs that takes the current node, destination node, adjacency list, visited set, and path vector as parameters and returns a boolean value indicating whether a path exists.
  • Recursively run the dfs function for each unvisited neighbor of the current node while keeping track of the path.
  • If at any point the current node is equal to the destination node, return true.
  • If the destination node is not reachable, clear the last element from the path vector and return false.
  • Now define a function findPath that takes src and dest as parameters. This function will call the dfs function and return the path if it exists.

C++ Program for DFS Path Finding

Below is a C++ implementation of the DFS algorithm to find a path between two vertices in a directed graph:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;

// Graph represented as an adjacency list
class Graph {
    unordered_map<int, vector<int>> adj;

public:
    // Add edge (for undirected graph)
    void addEdge(int u, int v) {
        adj[u].push_back(v);
        adj[v].push_back(u); // Omit this for directed graph
    }

    // DFS helper to find path
    bool dfs(int current, int destination, unordered_set<int>& visited, vector<int>& path) {
        visited.insert(current);
        path.push_back(current);

        if (current == destination)
            return true;

        for (int neighbor : adj[current]) {
            if (visited.find(neighbor) == visited.end()) {
                if (dfs(neighbor, destination, visited, path))
                    return true;
            }
        }

        path.pop_back(); // Backtrack
        return false;
    }

    // Main function to find path
    vector<int> findPath(int source, int destination) {
        unordered_set<int> visited;
        vector<int> path;

        if (dfs(source, destination, visited, path))
            return path;
        else
            return {}; // Empty vector indicates no path
    }
};

// Driver code
int main() {
    Graph g;

    // Add edges
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 3);
    g.addEdge(3, 4);
    g.addEdge(5, 6); // disconnected component

    int source = 1, destination = 4;

    vector<int> path = g.findPath(source, destination);

    if (!path.empty()) {
        cout << "Path from " << source << " to " << destination << ": ";
        for (int node : path)
            cout << node << " ";
        cout << endl;
    } else {
        cout << "No path found from " << source << " to " << destination << endl;
    }

    return 0;
}

The output of above code will be:

Path from 1 to 4: 1 0 2 3 4 

Conclusion

In this article, we explained DFS and BFS algorithms to find a path between two vertices in a directed graph. The important thing to note is that these algorithms not necessarily return the shortest path, but they do confirm the existence of at least one path between the two vertices. The BFS algorithm is generally more suitable for finding the shortest path in unweighted graphs and DFS algorithm is able to find all the possible paths between two vertices.

Farhan Muhamed
Farhan Muhamed

No Code Developer, Vibe Coder

Updated on: 2025-07-30T15:31:43+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements