Minimum spanning tree (Prim's)

Grow one tree outward from a start node, always adding the cheapest edge that reaches a new node.

Time O(E log V)Space O(V)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Keep a frontier of candidate edges leaving the tree built so far. Always take the cheapest one. If it reaches a node already in the tree, it would only create a cycle, so skip it; otherwise the new node joins the tree and its edges become new candidates.

Code

public static List<(char, char, int)> Prim(
        Dictionary<char, List<(char to, int w)>> graph, char start) {
    var inTree = new HashSet<char> { start };
    var pq = new PriorityQueue<(char u, char v, int w), int>();
    foreach (var (v, w) in graph[start]) pq.Enqueue((start, v, w), w);
    var tree = new List<(char, char, int)>();
    while (pq.Count > 0) {
        var (u, v, w) = pq.Dequeue();
        if (inTree.Contains(v)) continue; // both ends already joined, skip
        inTree.Add(v);
        tree.Add((u, v, w));
        foreach (var (x, wx) in graph[v])
            if (!inTree.Contains(x)) pq.Enqueue((v, x, wx), wx);
    }
    return tree;
}
class Edge { char to; int w; }   // one weighted edge: where it goes and what it costs

static List<int[]> prim(
        Map<Character, List<Edge>> graph, char start) {
    Set<Character> inTree = new HashSet<>(); inTree.add(start);
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]); // {u, v, w} by weight
    for (Edge e : graph.get(start)) pq.offer(new int[]{start, e.to, e.w});
    List<int[]> tree = new ArrayList<>();
    while (!pq.isEmpty()) {
        int[] top = pq.poll(); char u = (char) top[0], v = (char) top[1]; int w = top[2];
        if (inTree.contains(v)) continue; // both ends already joined, skip
        inTree.add(v);
        tree.add(new int[]{u, v, w});
        for (Edge e : graph.get(v))
            if (!inTree.contains(e.to)) pq.offer(new int[]{v, e.to, e.w});
    }
    return tree;
}
vector<tuple<char, char, int>> prim(
        unordered_map<char, vector<pair<char, int>>>& graph, char start) {
    unordered_set<char> inTree{start};
    priority_queue<tuple<int, char, char>, vector<tuple<int, char, char>>, greater<>> pq; // {w, u, v}
    for (auto [v, w] : graph[start]) pq.push({w, start, v});
    vector<tuple<char, char, int>> tree;
    while (!pq.empty()) {
        auto [w, u, v] = pq.top(); pq.pop();
        if (inTree.count(v)) continue; // both ends already joined, skip
        inTree.insert(v);
        tree.push_back({u, v, w});
        for (auto [x, wx] : graph[v])
            if (!inTree.count(x)) pq.push({wx, v, x});
    }
    return tree;
}
import heapq

def prim(graph: dict[str, list[tuple[str, int]]], start: str) -> list[tuple[str, str, int]]:
    in_tree = {start}
    pq = []
    for v, w in graph[start]: heapq.heappush(pq, (w, start, v))
    tree = []
    while pq:
        w, u, v = heapq.heappop(pq)
        if v in in_tree: continue  # both ends already joined, skip
        in_tree.add(v)
        tree.append((u, v, w))
        for x, wx in graph[v]:
            if x not in in_tree: heapq.heappush(pq, (wx, v, x))
    return tree

Tips

In the .NET library

Prim grows one connected tree outward, while Kruskal picks edges globally by weight regardless of which tree they touch. On the same graph with distinct weights they produce the same tree, just discovered in a different order.