Graph Theory37 sections · 1633 units
Open in Course

Prim's Algorithm - Pseudocode

(Step-by-step implementation)

Here is Prim's algorithm:

function prim(n, adj, start):
    visited = array of size n, all false
    pq = min-heap
    mst = empty list

    visited[start] = true
    for (v, w) in adj[start]:
        pq.push((w, start, v))

    while pq is not empty:
        (w, u, v) = pq.pop()
        if visited[v]:
            continue
        visited[v] = true
        mst.append((u, v, w))
        for (next, weight) in adj[v]:
            if not visited[next]:
                pq.push((weight, v, next))

    return mst

You will visit exactly nn nodes if the graph is connected.