Back to the 2023 paper

Module 3: Graph and Tree Algorithms

20237m

What is minimum spanning tree (MST)? Explain the steps of Prim's algorithm to find the MST using an example.

Worked SolutionAI Assisted

MST & Prim's Algorithm (Detailed)

MST Definition

Connected, undirected, weighted G(V,E,w)G(V,E,w). Spanning tree TT with V−1V-1 edges spanning all vertices. MST minimizes ∑e∈Tw(e)\sum_{e\in T} w(e).

Prim's Algorithm (as in Q94)

Prim(G, r):
  key[v]=∞, parent[v]=NIL, inQueue[v]=true for all v
  key[r]=0; Q = min-heap on key
  while Q≠∅:
    u=Extract-Min(Q); inQueue[u]=false
    for v in Adj[u]:
      if inQueue[v] and w(u,v)<key[v]:
        parent[v]=u; key[v]=w(u,v); Decrease-Key(Q,v,key[v])

Cut property ensures each added edge is safe.

Example Run (Graph: V=4 edges AB1 AC4 BC2 BD5 CD3)

Start A: key[A]=0

  • Extract A → relax B1, C4 → key[B]=1 parent A, key[C]=4
  • Extract B (min1) → relax C via2 <4 → key[C]=2 parent B; D via5 → key[D]=5
  • Extract C (2) → relax D via3 <5 → key[D]=3 parent C
  • Extract D (3) → done. MST edges: AB1, BC2, CD3 weight 6.

Complexity: O(Elog⁡V)O(E\log V) binary heap, O(V2)O(V^2) array, O(E+Vlog⁡V)O(E+V\log V) Fibonacci.

When to Use Prim vs Kruskal

  • Prim vertex-growth → dense graphs (O(V2)O(V^2) without heap good).
  • Kruskal edge-sort → sparse graphs (O(Elog⁡E)O(E\log E)). Both O(Elog⁡V)O(E\log V) order-wise.

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.