# Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method

Given a connected acyclic graph, a source vertex and a destination vertex, your task is to count the number of vertices between the given source and destination vertex by Disjoint Union Method .

Examples:

Input : 1 4
4 5
4 2
2 6
6 3
1 3
Output : 3
In the input 6 is the total number of vertices
labeled from 1 to 6 and the next 5 lines are the connection
between vertices. Please see the figure for more
explanation. And in last line 1 is the source vertex
and 3 is the destination vertex. From the figure
it is clear that there are 3 nodes(4, 2, 6) present
between 1 and 3.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

To use the disjoint union method we have to first check the parent of each of the node of the given graph. We can use BFS to traverse through the graph and calculate the parent vertex of each vertices of graph. For example, if we traverse the graph (i.e starts our BFS) from vertex 1 then 1 is the parent of 4, then 4 is the parent of 5 and 2, again 2 is the parent of 6 and 6 is the parent of 3 .
Now to calculate the number of nodes between the source node and destination node, we have to make a loop that starts with parent of the destination node and after every iteration we will update this node with parent of current node, keeping the count of the number of iterations. The execution of the loop will terminate when we reach the source vertex and the count variable gives the number of nodes in the connection path of the source node and destination node.
In the above method, the disjoint sets are all the sets with a single vertex, and we have used union operation to merge two sets where one contains the parent node and other contains the child node.

Below are implementations of above approach .

## Python3

Output:

3

Time Complexity: O(n), where n is total number of nodes in the graph.

## tags:

Graph union-find Graph union-find