Spanning Trees: Spanning Trees: A Subgraph T of A Undirected Graph G (V, E) Is A Spanning Tree of G If It Is A
Spanning Trees: Spanning Trees: A Subgraph T of A Undirected Graph G (V, E) Is A Spanning Tree of G If It Is A
i) Prim's algorithm
Rather than build a subgraph one edge at a time, Prim's algorithm builds a tree one vertex at a
time.
Prim's algorithm:
let T be a single vertex x
while (T has fewer than n vertices)
{
find the smallest edge connecting T to G-T
add it to T
}
Since each edge added is the smallest connecting T to G-T, we only add edges that should be
part of the MST.
Again, it looks like the loop has a slow step in it. But again, some data structures can be used
to speed this up. The idea is to use a heap to remember, for each vertex, the smallest edge
connecting T with that vertex.
This algorithm is known as a greedy algorithm, because it chooses at each step the cheapest
edge to add to S. You should be very careful when trying to use greedy algorithms to solve
other problems, since it usually doesn't work. E.g. if you want to find a shortest path from a
to b, it might be a bad idea to keep taking the shortest edges.