Prim's MST visualization
Grow one tree by always adding the cheapest edge leaving it.
Start from any vertex. Among all edges that connect the tree to a vertex outside it, pick the lightest — the cut property guarantees it belongs to some minimum spanning tree.
Edge case: on a disconnected graph no spanning tree exists; Prim only spans the start vertex's component.
Complexity
Time: best O(E log V), average O(E log V), worst O(E log V). Space: O(V + E). Difficulty: Intermediate.
Pseudocode
procedure prim(G, s):
inTree ← {s}; pq ← edges leaving s
while pq not empty:
(w, u, v) ← pq.popMin()
if v in inTree: continue // would form a cycle
add edge (u, v) to MST; inTree.add(v)
push edges from v to vertices outside the tree
if |inTree| < |V|: graph is disconnectedMore graphs algorithms
- Breadth-First Search — Explore level by level with a queue — gives shortest paths in unweighted graphs.
- Depth-First Search — Go as deep as possible along each branch before backtracking.
- Dijkstra's Shortest Path — Greedily settle the closest unsettled vertex using a priority queue.
- Bellman–Ford — Relax every edge V−1 times; handles negative weights and detects negative cycles.
- Kruskal's MST — Sort edges by weight and add each one unless it would create a cycle (union–find).
- Topological Sort (Kahn) — Order a DAG so every edge points forward, by repeatedly removing zero in-degree vertices.
- Floyd–Warshall — All-pairs shortest paths by allowing one more intermediate vertex k at a time.
- A* Pathfinding — Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.