Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This tutorial will guide you through the steps of implementing Prim's algorithm.

Steps of Prim's Algorithm

  1. Initialize:

    • Create a set S that will contain all the vertices included in the MST.
    • Create a set Q that will contain all the vertices not yet included in the MST.
    • Set all vertices in Q as their own parent.
    • Set all vertices in Q as having a distance of infinity from the MST.
    • Set the distance of the first vertex in Q to 0.
  2. Select the vertex with the smallest distance:

    • Select the vertex u in Q with the smallest distance.
  3. Add u to S:

    • Add u to S.
  4. Update the distances:

    • For each vertex v in Q that is adjacent to u:
      • If the distance of v through u is less than the current distance of v, update the distance of v to be the distance through u and set u as the parent of v.
  5. Repeat steps 2-4:

    • Repeat steps 2-4 until all vertices in Q have been added to S.

Example

Here's an example of how Prim's algorithm works on a graph:

A -- 2 -- B
|       |
5       1
|       |
C -- 3 -- D

If we start with vertex A, the MST will be A-B-C-D.

Code Implementation

You can implement Prim's algorithm in various programming languages. Here's an example in Python:

def prims_algorithm(graph):
    # Initialize MST and distances
    mst = []
    distances = {vertex: float('inf') for vertex in graph}
    distances[0] = 0  # Start with vertex 0

    while len(mst) < len(graph):
        # Find the vertex with the smallest distance
        u = min(distances, key=distances.get)

        # Add the vertex to the MST
        mst.append(u)

        # Update the distances of the adjacent vertices
        for v in graph[u]:
            if distances[v] > distances[u] + graph[u][v]:
                distances[v] = distances[u] + graph[u][v]

    return mst

# Example graph
graph = {
    0: {1: 2, 2: 5},
    1: {0: 2, 2: 1, 3: 3},
    2: {0: 5, 1: 1, 3: 3},
    3: {1: 3, 2: 3}
}

# Run Prim's algorithm
mst = prims_algorithm(graph)
print("MST:", mst)

For more information on Prim's algorithm, you can read our in-depth article on the topic.

Prim's Algorithm Graph