Prim's algorithm in Javascript

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.

The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex.

How Prim's Algorithm Works

Let us look at an illustration of how Prim's algorithm works:

1. Choose any arbitrary node as the root node: In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any node can be the root node. Any vertex can be a root node because in the spanning tree all nodes of a graph are included and because it is connected, there must be at least one edge which will join it to the rest of the tree.

2. Check outgoing edges and select the one with less cost: After choosing the root node S, we see that S-A and S-C are two edges with weights 7 and 8, respectively. We choose the edge S-A as it has lesser weight.

S A C D 7 8 3 3

Now, the tree S-A is treated as one node and we check for all edges going out from it. We select the one which has the lowest cost and include it in the tree.

After this step, we continue adding the minimum weight edges that connect new vertices to our growing tree until all vertices are included.

Implementation

primsMST() {
    // Initialize graph that'll contain the MST
    const MST = new Graph();
    if (this.nodes.length === 0) {
        return MST;
    }

    // Select first node as starting node
    let s = this.nodes[0];

    // Create a Priority Queue and explored set
    let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length);
    let explored = new Set();
    explored.add(s);
    MST.addNode(s);

    // Add all edges from this starting node to the PQ taking weights as priority
    this.edges[s].forEach(edge => {
        edgeQueue.enqueue([s, edge.node], edge.weight);
    });

    // Take the smallest edge and add that to the new graph
    let currentMinEdge = edgeQueue.dequeue();
    while (!edgeQueue.isEmpty()) {

        // Continue removing edges till we get an edge with an unexplored node
        while (!edgeQueue.isEmpty() && explored.has(currentMinEdge.data[1])) {
            currentMinEdge = edgeQueue.dequeue();
        }
        let nextNode = currentMinEdge.data[1];

        // Check again as queue might get empty without giving back unexplored element
        if (!explored.has(nextNode)) {
            MST.addNode(nextNode);
            MST.addEdge(currentMinEdge.data[0], nextNode, currentMinEdge.priority);
            
            // Again add all edges to the PQ
            this.edges[nextNode].forEach(edge => {
                edgeQueue.enqueue([nextNode, edge.node], edge.weight);
            });

            // Mark this node as explored
            explored.add(nextNode);
            s = nextNode;
        }
        currentMinEdge = edgeQueue.dequeue();
    }
    return MST;
}

Example Usage

let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");

g.addEdge("A", "C", 100);
g.addEdge("A", "B", 3);
g.addEdge("A", "D", 4);
g.addEdge("C", "D", 3);
g.addEdge("D", "E", 8);
g.addEdge("E", "F", 10);
g.addEdge("B", "G", 9);

g.primsMST().display();

Output

This will give the output:

A->B, D
B->A, G
D->A, C, E
C->D
E->D, F
G->B
F->E

Graph Representation

Our initial graph structure:

/**
 *       A
 *      /|\
 *     C | B
 *     \| |
 *      D G
 *      |/
 *      E
 *      |
 *      F
 */

After applying Prim's algorithm, our minimum spanning tree looks like:

/**
 *       A
 *       |\
 *    C  | B
 *     \ | |
 *      D   G
 *      |
 *      E
 *      |
 *      F
 */

Key Points

  • Prim's algorithm uses a greedy approach to build the MST
  • It starts from any arbitrary vertex
  • At each step, it adds the minimum weight edge that connects a new vertex to the existing tree
  • Time complexity: O(E log V) using a priority queue
  • Space complexity: O(V) for storing the explored set

Conclusion

Prim's algorithm efficiently finds the minimum spanning tree by greedily selecting the smallest weight edges. The algorithm guarantees an optimal solution and is widely used in network design and clustering applications.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements