According to GeeksForGeeks, the steps to find Minimal Spanning Tree in an undirected graph are :
- Sort all the edges in non-decreasing order of their weight.
- 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.
- 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.
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.