# 25.2 Prim's Algorithm

One way to find the MST of a graph is the Prim's Algorithm. In this section, we will discuss both the conceptual and concrete implementation of this algorithm, as well as its runtime analysis.&#x20;

## Conceptual Visualization

{% embed url="<https://www.youtube.com/watch?v=ZCMTccvfaTQ>" %}

Prim's Algorithm is one way to find a MST from a graph. It is as follows:

1. Start from some arbitrary node.
2. Repeatedly add the shortest edge that has **one node inside the MST in construction.**
3. Repeat until there are V - 1 edges.

### Why does it work?

Prim's algorithm works because at all stages of the algorithm, we can reason as follows:&#x20;

* Consider dividing all the nodes in the graph into two sets:
  * Set 1: nodes that are part of the existing MST that's under construction
  * Set 2: all other nodes
* According to the algorithm, we always add the **lightest, or minimally weighted, edge** that crosses this cut.
* By **the Cut Property**, the added edge is necessarily part of the final MST.

## Implementation

{% embed url="<https://www.youtube.com/watch?v=JoS9ZegarJs>" %}

Essentially, this algorithm runs via the same mechanism as [Dijkstra's algorithm](/cs61b-textbook/24.-shortest-paths/24.2-dijkstras-algorithm.md).&#x20;

The only difference is that while Dijkstra's considers candidate nodes by their distance from the source node, Prim's looks at each candidate node's **distance from the MST under construction.**

## Runtime Analysis&#x20;

Because this algorithm runs through the same mechanism as Dijkstra's algorithm, its runtime is also identical to Dijkstra's:

$$
O((|V| + |E| )log(|V|))
$$

Remember, this is because we need to add to a priority queue fringe once for every edge we have, and we need to dequeue from it once for every vertex we have.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs61b-2.gitbook.io/cs61b-textbook/25.-minimum-spanning-trees/25.2-prims-algorithm.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
