Algo-Sim › Advanced Graphs

Minimum Spanning Tree (Prim)

Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input

Connect all nodes with the cheapest set of edges. Prim: grow one tree from node 0, always adding the cheapest edge that leaves it, using a min-heap.

Problem

Given a connected undirected graph with nodes 0..n − 1 and weighted edges, return the total weight of a minimum spanning tree. This version uses Prim's algorithm, growing one tree from node 0.

Constraints

Edge cases to test

Follow-up questions

What is the cost?
O(E log V) with a binary heap and lazy deletion; O(V²) with an array, which suits dense graphs.
Why is the cheapest crossing edge always safe?
The cut property: for any cut, a lightest edge across it belongs to some MST.

Solution

Java

public int minimumSpanningTree(int n, int[][] edges) {
    List<List<int[]>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        adj.get(e[0]).add(new int[] { e[1], e[2] });
        adj.get(e[1]).add(new int[] { e[0], e[2] });
    }
    boolean[] inTree = new boolean[n];
    // Entries are { weight, node }: the cheapest known edge into node.
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    pq.offer(new int[] { 0, 0 });
    int total = 0, count = 0;
    while (!pq.isEmpty() && count < n) {
        int[] top = pq.poll();
        if (inTree[top[1]]) continue;
        inTree[top[1]] = true;
        total += top[0];
        count++;
        for (int[] e : adj.get(top[1])) {
            if (!inTree[e[0]]) pq.offer(new int[] { e[1], e[0] });
        }
    }
    return count == n ? total : -1;
}

Python

import heapq


def minimum_spanning_tree(n, edges):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
        adj[v].append((u, w))
    in_tree = [False] * n
    # Entries are (weight, node): the cheapest known edge into node.
    pq = [(0, 0)]
    total = count = 0
    while pq and count < n:
        w, u = heapq.heappop(pq)
        if in_tree[u]:
            continue
        in_tree[u] = True
        total += w
        count += 1
        for v, wv in adj[u]:
            if not in_tree[v]:
                heapq.heappush(pq, (wv, v))
    return total if count == n else -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minimumSpanningTree(int n, vector<vector<int>> &edges) {
        vector<vector<vector<int>>> adj = {};
        for (int i = 0; i < n; i++)
            adj.push_back({});
        for (vector<int> &e : edges) {
            adj[e[0]].push_back(vector<int>{e[1], e[2]});
            adj[e[1]].push_back(vector<int>{e[0], e[2]});
        }
        vector<bool> inTree = vector<bool>(n);
        // Entries are { weight, node }: the cheapest known edge into node.
        priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
        pq.push(vector<int>{0, 0});
        int total = 0, count = 0;
        while (!pq.empty() && count < n) {
            vector<int> top = pq.top();
            pq.pop();
            if (inTree[top[1]])
                continue;
            inTree[top[1]] = true;
            total += top[0];
            count++;
            for (vector<int> &e : adj[top[1]]) {
                if (!inTree[e[0]])
                    pq.push(vector<int>{e[1], e[0]});
            }
        }
        return count == n ? total : -1;
    }
};

More Advanced Graphs problems