Can we use n(V) <= n(E) to detect cycle while using Kruskal's MST for an undirected graph?

155 views Asked by At

According to GeeksForGeeks, the steps to find Minimal Spanning Tree in an undirected graph are :

  1. Sort all the edges in non-decreasing order of their weight.
  2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.
  3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Here, for step #2, a Union Find algorithm is used.

Instead of this approach what if we check for the following conditions:

(number of vertices already included in the graph) <= (number of edges already included in the graph). I believe if the above condition is true, there will be a cycle (Since there will not be any vertex which has a degree 0)

Is there anything wrong with my approach? Although the time complexity remains the same since we are still sorting the edges, this approach could reduce the time taken and code complexity to execute step #2.

2

There are 2 answers

3
Maurycyt On BEST ANSWER

No, you cannot use this, because you can encounter a cycle in a graph, for which n(V) > n(E).

For example, the graph consists of 4 vertices, and there are three edges, 1-2, 2-3, and 1-3. There is a cycle, but it is not true that n(V) <= n(E).

Essentially, what you did is detect a cycle if n(V) <= n(E), but you did not prove, that cycles are limited only to cases when that is true.

0
harsh On

As told by @Maurycat, this won't hold when there are two components in a graph and one of the components has a cycle.