C++ Program to Find Path Between Two Nodes in a Graph



In this article, we will learn how to find a path between two nodes in an undirected graph and implement it in C++. We will represent graph as an adjacency list and use a depth-first search (DFS) algorithm to find the path. We already discussed finding a path between two nodes in a directed graph, check here.

Finding Path Between Two Nodes in an Undirected Graph

We have an adjacency list representation of an undirected graph adj[] and two nodes src and dest, our task is to write a program that finds the path between the src and dest nodes of the graph if it exists. If not, we will return an empty vector. To understand better consider the following graph:

Graph Representation

Example Scenario 1

Consider the following input/output scenario:

Input:
adjList = [ 0 -> [1, 2], 1 -> [0, 2],
            2 -> [0, 1, 4], 3 -> [5],
            4 -> [2], 5 -> [3, 6],
            6 -> [5]
          ]
src = 0
dest = 4

Output:
[0, 1, 2, 4]

Explanation: The path from node 0 to node 4 is [0, 1, 2, 4]. We start at node 0, go to node 1, then to node 2, and finally reach node 4.

Example Scenario 2

Consider another input/output scenario:

Input:
adjList = [ 0 -> [1, 2], 1 -> [0, 2],
            2 -> [0, 1, 4], 3 -> [5],
            4 -> [2], 5 -> [3, 6],
            6 -> [5]
          ]
src = 3
dest = 4

Output:
No path exists

Explanation: There is no path from node 3 to node 4 in the given graph. The nodes 3 and 4 are not connected.

DFS Algorithm to Find Path Between Two Nodes

To find a path between two nodes in an undirected graph, we can use the Depth-First Search (DFS) algorithm. The DFS algorithm explores as far as possible along each branch before backtracking. We will modify this algorithm slightly to keep track of the path from the source node to the destination node.

Here is the steps that we can follow to find the path between two nodes:

  • 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++ Code to Find Path Between Two Nodes

Here is the C++ code that implements the above algorithm to find a path between two nodes in an undirected 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(1, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(3, 5);
    g.addEdge(5, 4);
    g.addEdge(4, 6);

    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 the above code will be:

Path from 1 to 4: 1 2 4

Time and Space Complexity

Time Complexity: The time complexity of the above algorithm is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Space Complexity: The space complexity is O(V). This is due to the storage of the adjacency list, visited set, and path vector.

Farhan Muhamed
Farhan Muhamed

No Code Developer, Vibe Coder

Updated on: 2025-07-30T15:36:29+05:30

849 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements