Prim's Algorithm in C++ — Greedy MST with a Priority Queue

Explore this blog post in detail

Blog Images

3 images
Blog Images - Image 1
Swipe
1 / 3

Prim's Algorithm in C++ — Greedy MST with a Priority Queue

Mashrur Rahman
8/12/2025
Graph Algorithms
Published
# Prim's Algorithm — Build MST using Greedy Selection (C++) ## Overview Prim's algorithm grows an MST from a starting vertex by always selecting the lightest edge that connects the tree to a vertex outside it. Using a min-priority queue yields **O(E log V)**. ## Implementation notes The repo `Prim.cpp` uses an adjacency list and a `priority_queue` (min-heap via `greater<>`) to select the smallest-frontier edge. Parent (`p[]`) and weight (`w[]`) arrays track the MST structure. Full file: `https://github.com/mashrur-rahman-fahim/algorithm/blob/main/Prim.cpp` ### Core idea - Initialize `w[]` with `∞`, pick start node `0` with `w[0]=0`. - Push all (`w[i]`, i) into the queue; pop min, mark visited, examine neighbors and relax. ## Complexity - Time: **O(E log V)** - Space: **O(V + E)** ## Output The program prints chosen edges and the total cost. ## Practical notes - For dense graphs using an adjacency matrix, Prim can be implemented in **O(V^2)**. - Ensure edges are added symmetrically for undirected graphs. ## Source `https://github.com/mashrur-rahman-fahim/algorithm/blob/main/Prim.cpp`.

Technologies & Tools

C++Graph AlgorithmsPrimPriority QueueVS CodeG++ CompilerGitGitHub

About the Author

External Links

Blog Info

Status:Published
Type:Algorithm Analysis
Category:Graph Algorithms
Author:Mashrur Rahman
Created:8/12/2025

About the Author

M

Mashrur Rahman

Blog Author

Comments (0)

No comments yet. Be the first to comment!

Mashrur Rahman

A passionate full-stack developer dedicated to creating innovative digital solutions that make a difference. Let's build something amazing together.

Get In Touch

Email

mashrur9550@gmail.com

Location

Dhaka, Bangladesh

© 2026 Mashrur Rahman. All rights reserved.