0

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.

harsh
  • 83
  • 8

2 Answers2

0

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.

Maurycyt
  • 676
  • 3
  • 19
  • This case will never arise when dealing with Kruskal's algorithm. A vertex will be added to the set only when it has an edge. This is exactly why I think my assumption will hold true – harsh Oct 07 '20 at 15:31
  • Ok then assume you have a graph with a lot of vertices and you connect 1-2, then 3-4 and then 5-6. Next, you connect 1-3. Right now, you have 6 vertices in the set (if I understand your method correctly) and only 4 edges. Thus, you can make a connection 2-4, which creates a cycle, but you won't detect it. Perhaps you mean something else, but in that case what happens if you connect two previously unconnected components with multiple edges? Overall, could you elaborate what you exactly mean by "already included in the graph"? – Maurycyt Oct 07 '20 at 15:41
  • Didn't take that case into consideration Thanks! – harsh Oct 07 '20 at 15:51
0

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

harsh
  • 83
  • 8