Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph.
Examples:
Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}
Output: 3
Explanation:
The path between 7 and 8 is 7 -> 2 -> 6 -> 3 -> 8.
So, the number of nodes between 7 and 8 is 3.

Input: V = 8, E = 7, src = 5, dest = 2, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}
Output: 1
Explanation:
The path between 5 and 2 is 5 -> 4 -> 2.
So, the number of nodes between 5 and 2 is 1.
Approach: The problem can also be solved using the Disjoint Union method as stated in this article. Another approach to this problem is to solve using the Depth First Search method. Follow the steps below to solve this problem:
- Initialize a visited array vis[] to mark which nodes are already visited. Mark all the nodes as 0, i.e., not visited.
- Perform a DFS to find the number of nodes present in the path between src and dest.
- The number of nodes between src and dest is equal to the difference between the length of the path between them and 2, i.e., (pathSrcToDest – 2).
- Since the graph is acyclic and connected, there will always be a single path between src and dest.
Below is the implementation of the above algorithm.
C++
#include <bits/stdc++.h>
using namespace std;
int dfs( int src, int dest, int * vis,
vector< int >* adj)
{
vis[src] = 1;
if (src == dest) {
return 1;
}
for ( int u : adj[src]) {
if (!vis[u]) {
int temp = dfs(u, dest, vis, adj);
if (temp != 0) {
return temp + 1;
}
}
}
return 0;
}
int countNodes( int V, int E, int src, int dest,
int edges[][2])
{
vector< int > adj[V + 1];
for ( int i = 0; i < E; i++) {
adj[edges[i][0]].push_back(edges[i][1]);
adj[edges[i][1]].push_back(edges[i][0]);
}
int vis[V + 1] = { 0 };
int count = dfs(src, dest, vis, adj);
return count - 2;
}
int main()
{
int V = 8, E = 7;
int src = 5, dest = 2;
int edges[][2]
= { { 1, 4 }, { 4, 5 },
{ 4, 2 }, { 2, 6 },
{ 6, 3 }, { 2, 7 },
{ 3, 8 } };
cout << countNodes(V, E, src, dest, edges);
return 0;
}
|
Java
import java.util.Vector;
class GFG{
static int dfs( int src, int dest, int []vis,
Vector<Integer> []adj)
{
vis[src] = 1 ;
if (src == dest)
{
return 1 ;
}
for ( int u : adj[src])
{
if (vis[u] == 0 )
{
int temp = dfs(u, dest,
vis, adj);
if (temp != 0 )
{
return temp + 1 ;
}
}
}
return 0 ;
}
static int countNodes( int V, int E,
int src, int dest,
int edges[][])
{
Vector<Integer> []adj = new Vector[V + 1 ];
for ( int i = 0 ; i < adj.length; i++)
adj[i] = new Vector<Integer>();
for ( int i = 0 ; i < E; i++)
{
adj[edges[i][ 0 ]].add(edges[i][ 1 ]);
adj[edges[i][ 1 ]].add(edges[i][ 0 ]);
}
int vis[] = new int [V + 1 ];
int count = dfs(src, dest,
vis, adj);
return count - 2 ;
}
public static void main(String[] args)
{
int V = 8 , E = 7 ;
int src = 5 , dest = 2 ;
int edges[][] = {{ 1 , 4 }, { 4 , 5 },
{ 4 , 2 }, { 2 , 6 },
{ 6 , 3 }, { 2 , 7 },
{ 3 , 8 }};
System.out.print(countNodes(V, E,
src, dest,
edges));
}
}
|
Python3
def dfs(src, dest, vis, adj):
vis[src] = 1
if (src = = dest):
return 1
for u in adj[src]:
if not vis[u]:
temp = dfs(u, dest, vis, adj)
if (temp ! = 0 ):
return temp + 1
return 0
def countNodes(V, E, src, dest, edges):
adj = [[] for i in range (V + 1 )]
for i in range (E):
adj[edges[i][ 0 ]].append(edges[i][ 1 ])
adj[edges[i][ 1 ]].append(edges[i][ 0 ])
vis = [ 0 ] * (V + 1 )
count = dfs(src, dest, vis, adj)
return count - 2
if __name__ = = '__main__' :
V = 8
E = 7
src = 5
dest = 2
edges = [ [ 1 , 4 ], [ 4 , 5 ],
[ 4 , 2 ], [ 2 , 6 ],
[ 6 , 3 ], [ 2 , 7 ],
[ 3 , 8 ] ]
print (countNodes(V, E, src, dest, edges))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int dfs( int src, int dest,
int []vis, List< int > []adj)
{
vis[src] = 1;
if (src == dest)
{
return 1;
}
foreach ( int u in adj[src])
{
if (vis[u] == 0)
{
int temp = dfs(u, dest,
vis, adj);
if (temp != 0)
{
return temp + 1;
}
}
}
return 0;
}
static int countNodes( int V, int E,
int src, int dest,
int [,]edges)
{
List< int > []adj = new List< int >[V + 1];
for ( int i = 0; i < adj.Length; i++)
adj[i] = new List< int >();
for ( int i = 0; i < E; i++)
{
adj[edges[i, 0]].Add(edges[i, 1]);
adj[edges[i, 1]].Add(edges[i, 0]);
}
int []vis = new int [V + 1];
int count = dfs(src, dest,
vis, adj);
return count - 2;
}
public static void Main(String[] args)
{
int V = 8, E = 7;
int src = 5, dest = 2;
int [,]edges = {{1, 4}, {4, 5},
{4, 2}, {2, 6},
{6, 3}, {2, 7},
{3, 8}};
Console.Write(countNodes(V, E, src,
dest, edges));
}
}
|
Javascript
<script>
function dfs(src,dest,vis,adj)
{
vis[src] = 1;
if (src == dest)
{
return 1;
}
for (let u=0;u< adj[src].length;u++)
{
if (vis[adj[src][u]] == 0)
{
let temp = dfs(adj[src][u], dest,
vis, adj);
if (temp != 0)
{
return temp + 1;
}
}
}
return 0;
}
function countNodes(V,E,src,dest,edges)
{
let adj = new Array(V + 1);
for (let i = 0; i < adj.length; i++)
adj[i] = [];
for (let i = 0; i < E; i++)
{
adj[edges[i][0]].push(edges[i][1]);
adj[edges[i][1]].push(edges[i][0]);
}
let vis = new Array(V + 1);
for (let i=0;i<vis.length;i++)
{
vis[i]=0;
}
let count = dfs(src, dest,
vis, adj);
return count - 2;
}
let V = 8, E = 7;
let src = 5, dest = 2;
let edges = [[1, 4], [4, 5],
[4, 2], [2, 6],
[6, 3], [2, 7],
[3, 8]];
document.write(countNodes(V, E,
src, dest,
edges));
</script>
|
Time Complexity: O(V+E)
Auxiliary Space: O(V)