AiTechWorlds
AiTechWorlds
Watch Prim's algorithm grow a minimum spanning tree by adding the cheapest crossing edge, with synced code.
import heapq
def prim(adj, n):
in_mst = [False] * n
pq = [(0, 0)]; total = 0
while pq:
w, u = heapq.heappop(pq)
if in_mst[u]: continue
in_mst[u] = True; total += w
for v, wt in adj[u]:
if not in_mst[v]:
heapq.heappush(pq, (wt, v))
return totalPrim's algorithm grows a minimum spanning tree from a start node by repeatedly adding the cheapest edge that connects a new node to the tree.
| Time | O(E log V) |
| Space | O(V) |
| Graph | Undirected, weighted |
The Prim's Algorithm Visualizer animates how Prim's minimum spanning tree (MST) works: starting from one node, it repeatedly adds the cheapest edge that connects a new node to the growing tree. Prim's runs in O(E log V) with a priority queue, uses O(V) space, and always produces a tree of minimum total weight on a connected weighted graph.
Generate a graph
Click New Graph or set the node-count slider to create a random weighted graph.
Play the animation
Press Play to watch the cheapest crossing edge added each step; the running MST weight updates.
Step and scrub
Use Step Forward/Back or the timeline to inspect each edge choice.
Read the synced code
The highlighted pseudocode line tracks the edge selection; switch tabs for C++, Java, Python, or JavaScript.
100% Private — No Server Required
All processing happens directly in your browser. No data is uploaded, stored, or transmitted to any server.
Last reviewed on June 14, 2026 by the AiTechWorlds Tools Team. All processing runs locally in your browser.