C++ Program to Check if Path Exists in a Graph

This is a C++ Program to check and find if the path between two nodes exists. By running DFS on given graph we can find out whether path exists between two nodes.

Here is source code of the C++ Program to Find Path Between Two Nodes in a Graph. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <iostream>
  2. #include <list>
  3.  
  4. using namespace std;
  5.  
  6. // This class represents a directed graph using adjacency list representation
  7. class Graph
  8. {
  9.         int V; // No. of vertices
  10.         list<int> *adj; // Pointer to an array containing adjacency lists
  11.     public:
  12.         Graph(int V); // Constructor
  13.         void addEdge(int v, int w); // function to add an edge to graph
  14.         bool isReachable(int s, int d); // returns true if there is a path from s to d
  15. };
  16.  
  17. Graph::Graph(int V)
  18. {
  19.     this->V = V;
  20.     adj = new list<int> [V];
  21. }
  22.  
  23. void Graph::addEdge(int v, int w)
  24. {
  25.     adj[v].push_back(w); // Add w to v’s list.
  26. }
  27.  
  28. // A BFS based function to check whether d is reachable from s.
  29. bool Graph::isReachable(int s, int d)
  30. {
  31.     // Base case
  32.     if (s == d)
  33.         return true;
  34.  
  35.     // Mark all the vertices as not visited
  36.     bool *visited = new bool[V];
  37.     for (int i = 0; i < V; i++)
  38.         visited[i] = false;
  39.  
  40.     // Create a queue for BFS
  41.     list<int> queue;
  42.  
  43.     // Mark the current node as visited and enqueue it
  44.     visited[s] = true;
  45.     queue.push_back(s);
  46.  
  47.     // it will be used to get all adjacent vertices of a vertex
  48.     list<int>::iterator i;
  49.  
  50.     while (!queue.empty())
  51.     {
  52.         // Dequeue a vertex from queue and print it
  53.         s = queue.front();
  54.         queue.pop_front();
  55.  
  56.         // Get all adjacent vertices of the dequeued vertex s
  57.         // If a adjacent has not been visited, then mark it visited
  58.         // and enqueue it
  59.         for (i = adj[s].begin(); i != adj[s].end(); ++i)
  60.         {
  61.             // If this adjacent node is the destination node, then return true
  62.             if (*i == d)
  63.                 return true;
  64.  
  65.             // Else, continue to do BFS
  66.             if (!visited[*i])
  67.             {
  68.                 visited[*i] = true;
  69.                 queue.push_back(*i);
  70.             }
  71.         }
  72.     }
  73.  
  74.     return false;
  75. }
  76.  
  77. // Driver program to test methods of graph class
  78. int main()
  79. {
  80.     // Create a graph given in the above diagram
  81.     Graph g(4);
  82.     g.addEdge(0, 1);
  83.     g.addEdge(0, 2);
  84.     g.addEdge(1, 2);
  85.     g.addEdge(2, 0);
  86.     g.addEdge(2, 3);
  87.     g.addEdge(3, 3);
  88.  
  89.     cout << "Enter the source and destination vertices: (0-3)";
  90.     int u, v;
  91.     cin >> u >> v;
  92.     if (g.isReachable(u, v))
  93.         cout << "\nThere is a path from " << u << " to " << v;
  94.     else
  95.         cout << "\nThere is no path from " << u << " to " << v;
  96.  
  97.     int temp;
  98.     temp = u;
  99.     u = v;
  100.     v = temp;
  101.     if (g.isReachable(u, v))
  102.         cout << "\nThere is a path from " << u << " to " << v;
  103.     else
  104.         cout << "\nThere is no path from " << u << " to " << v;
  105.  
  106.     return 0;
  107. }

Output:

$ g++ PathBetweenNodes.cpp
$ a.out
 
Enter the source and destination vertices: (0-3)
1 3
 
There is a path from 1 to 3
There is no path from 3 to 1
 
Enter the source and destination vertices: (0-3)
2 3
 
There is a path from 2 to 3
There is no path from 3 to 2

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.