Can we detect cycles in directed graph using Union-Find data structure?

后端 未结 2 1316
轮回少年
轮回少年 2021-01-03 00:30

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

2条回答
  •  走了就别回头了
    2021-01-03 01:14

    Let me give you an example: Q1. Take an undirected graph:

    Pic1 Is there a cycle in above undirected graph? Yes. And we can find the cycle using Union-Find algo.

    Q2. Now look at the similar directed graph:

    Pic2

    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:

    Pic3 OR Pic4 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.

提交回复
热议问题