I have implemented a union find algorithm that finds and joins an undirected graph with vertexes that are represented by integers. I want to know if someone has any psuedocode or an idea on how to see if components “connected” ie there is a path that goes from one node to another. For example, I have the following vertexes:
7 (source vertex), 9 (destination vertex) and 8 (source vertex), 7 (destination vertex) are all connected. However, something like 3 (source vertex), 5 (destination vertex) would not be connected to the previous set of components. Could anyone guide me in the right direction or give me an idea on how to test this? Thanks!
Yes, all you do is test whether the two nodes have the same root. If you use path compression when you build your graph, this turns out to be very fast.
The sets are already identified by a common root node. After you have done all your unions, each unique set will have a single root. So you then run through each node and call
Findon it. How about this:Now you have a map containing all your sets as individual lists, and you can do what you like…
To make all these calls to
Findefficient, you should implement path compression in yourUnionfunction.