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 .
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 next 5 lines are connection between verticies . 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 .
To use 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 number of nodes between the source node and destination node, we have to make a loop that starts with parent of destination node and after every iteration we will update this node with parent of current node , keeping the count of number of iterations. The execution of loop will terminate when we reach the source vertex and the count variable gives the number of nodes in the connected path of source node and destination node.
In the above method the disjoint sets are all the sets with 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 .
Time Complexity: O(n), where n is total number of nodes in the graph.
This article is contributed by Surya Priy. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Find maximum number of edge disjoint paths between two vertices
- Minimum number of edges between two vertices of a Graph
- Disjoint Set Union on trees | Set 2
- Disjoint Set Union on trees | Set 1
- Clone a Directed Acyclic Graph
- All Topological Sorts of a Directed Acyclic Graph
- Shortest Path in Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Longest Path in a Directed Acyclic Graph
- DFS for a n-ary tree (acyclic graph) represented as adjacency list
- Assign directions to edges so that the directed graph remains acyclic
- Number of sink nodes in a graph
- Articulation Points (or Cut Vertices) in a Graph
- Construct a graph from given degrees of all vertices
Improved By : sanskar27jain