I know that one can detect cycles in direct graphs using DFS and BFS. I want to know whether we can detect cycles in directed graphs using Union-Find or not?
- If yes, then how? and
- If we can't, then why?
I know that one can detect cycles in direct graphs using DFS and BFS. I want to know whether we can detect cycles in directed graphs using Union-Find or not?
No, we cannot use union-find to detect cycles in a directed graph. This is because a directed graph cannot be represented using the disjoint-set(the data structure on which union-find is performed).
When we say 'a union b' we cannot make out the direction of edge
But, incase of undirected graphs, each connected component is equivalent to a set. So union-find can be used to detect a cycle. Whenever you try to perform union on two vertices belonging to the same connected component, we can say that cycle exists.
No.
Let me give you an example:
Is there a cycle in above undirected graph? Yes. And we can find the cycle using Union-Find algo.
Is there a cycle in above directed graph? No! BUT if you use Union-Find algo to detect cycle in above directed graph, it will say YES! Since union-find algo looks at the above diagram as below:
OR
Is there a cycle in above diagram? Yes! But the original(Q2) question was tampered and this is not what was asked. So Union-find algo will give wrong results for directed graphs.
No, we cannot use union-find to detect cycles in a directed graph. This is because a directed graph cannot be represented using the disjoint-set(the data structure on which union-find is performed).
When we say 'a union b' we cannot make out the direction of edge
is a going to b? (or) is b going to a? But, incase of unordered graphs, each connected component is equivalent to a set. So union-find can be used to detect a cycle. Whenever you try to perform union on two vertices belonging to the same connected component, we can say that cycle exists.
Just wanted to add to @Cherubim's answer, I just thought of this question that why can't we make out the direction of 'a union b' like we can consider it as a is connected to b right ('a union b' only nodes which are a->b)?
Well that will also fail, consider two nodes x and y, they are connected x -> y and they already have parents in the disjoint set, x_root and y_root. So what happens when we say 'x union y' (x is connected to y), we make y_root the parent of x_root. well this tells us that:
So the main problem beside ambiguous direction, is also that not every node in a directed graph is connected to each other.