{"id":20088,"date":"2025-11-27T06:28:55","date_gmt":"2025-11-27T06:28:55","guid":{"rendered":"https:\/\/www.kaashivinfotech.com\/blog\/?p=20088"},"modified":"2025-11-27T06:28:55","modified_gmt":"2025-11-27T06:28:55","slug":"prims-algorithm-explained","status":"publish","type":"post","link":"https:\/\/www.kaashivinfotech.com\/blog\/prims-algorithm-explained\/","title":{"rendered":"Prim\u2019s Algorithm \u2013 Explained with a Pseudocode Example"},"content":{"rendered":"<h2 data-start=\"1264\" data-end=\"1315\">What Is Prim\u2019s Algorithm?<\/h2>\n<blockquote data-start=\"1367\" data-end=\"1500\">\n<p data-start=\"1369\" data-end=\"1500\"><strong data-start=\"1369\" data-end=\"1500\">Prim\u2019s Algorithm is a greedy algorithm used to find a Minimum Spanning Tree (MST) from a weighted, connected, undirected graph.<\/strong><\/p>\n<\/blockquote>\n<p data-start=\"1502\" data-end=\"1571\">Yep \u2014 that\u2019s the one-line exam-ready answer. But let\u2019s make it human.<\/p>\n<p data-start=\"1573\" data-end=\"1703\">Think of Prims like building a road network between multiple cities using the minimum cost possible, without creating loops.<\/p>\n<p data-start=\"1705\" data-end=\"1844\">You start from one city (any city), pick the cheapest connection, then from the visited cities pick the next cheapest edge\u2026 and you repeat.<\/p>\n<p data-start=\"1705\" data-end=\"1844\"><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-20089 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm.webp\" alt=\"\" width=\"624\" height=\"292\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm.webp 762w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-300x141.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-380x178.webp 380w\" sizes=\"(max-width: 624px) 100vw, 624px\" \/><\/p>\n<h2 data-start=\"1705\" data-end=\"1844\"><strong>How Prim\u2019s Algorithm Works (Step-by-Step)<\/strong><\/h2>\n<ol data-start=\"2391\" data-end=\"2860\">\n<li data-start=\"2391\" data-end=\"2466\">\n<p data-start=\"2394\" data-end=\"2466\"><strong data-start=\"2394\" data-end=\"2413\">Pick any vertex<\/strong> as a starting point. Mark it \u201cvisited\u201d \/ \u201cin MST\u201d.<\/p>\n<\/li>\n<li data-start=\"2467\" data-end=\"2550\">\n<p data-start=\"2470\" data-end=\"2550\">Look at <strong data-start=\"2478\" data-end=\"2513\">all edges from visited vertices<\/strong> that go to <strong data-start=\"2525\" data-end=\"2547\">unvisited vertices<\/strong>.<\/p>\n<\/li>\n<li data-start=\"2551\" data-end=\"2666\">\n<p data-start=\"2554\" data-end=\"2666\">Choose the <strong data-start=\"2565\" data-end=\"2598\">edge with the smallest weight<\/strong> among them. Add that edge + the new vertex to MST (mark visited).<\/p>\n<\/li>\n<li data-start=\"2667\" data-end=\"2791\">\n<p data-start=\"2670\" data-end=\"2791\">Update the list of \u201ccandidate edges\u201d: now include edges from this newly added vertex (that lead to unvisited vertices).<\/p>\n<\/li>\n<li data-start=\"2792\" data-end=\"2860\">\n<p data-start=\"2795\" data-end=\"2860\">Repeat steps 2\u20134 until <strong data-start=\"2818\" data-end=\"2857\">all vertices are visited \/ included<\/strong>.<\/p>\n<\/li>\n<\/ol>\n<p data-start=\"2862\" data-end=\"3020\">Because we always pick the cheapest available edge that expands the tree \u2014 we ensure the total cost remains minimal.<\/p>\n<p data-start=\"3022\" data-end=\"3137\">This greedy, \u201cgrow-step-by-step\u201d nature makes Prim\u2019s algorithm efficient and intuitive when you visualize graphs.<\/p>\n<h2 data-start=\"3022\" data-end=\"3137\">Pseudocode for Prim\u2019s Algorithm<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">function Prim(graph):\r\n    MST = empty set of edges\r\n    start = any vertex in graph\r\n    visited = { start }\r\n    candidateEdges = all edges from start\r\n\r\n    while visited does not include all vertices:\r\n        edge = the edge from candidateEdges with minimum weight\r\n        (u, v, w) = edge   \/\/ u: visited side, v: unvisited side\r\n        add edge to MST\r\n        add v to visited\r\n        remove that edge from candidateEdges\r\n        add to candidateEdges all edges from v that lead to unvisited vertices\r\n\r\n    return MST\r\n<\/pre>\n<p data-start=\"3708\" data-end=\"3839\"><em data-start=\"3708\" data-end=\"3839\">(Note: Implementation details \u2014 like how you store edges, pick minimum efficiently \u2014 may vary depending on graph representation.)<\/em><\/p>\n<p data-start=\"3841\" data-end=\"3968\">This pseudocode aligns with common textbook\/explanation versions of <a href=\"https:\/\/www.wikitechy.com\/technology\/prims-minimum-spanning-tree-mst\/\" target=\"_blank\" rel=\"noopener\">Prim\u2019s algorithm<\/a>.<\/p>\n<h2 data-start=\"3841\" data-end=\"3968\">Example Implementation (Python)<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import heapq\r\n\r\ndef prim(graph, start):\r\n    visited = set([start])\r\n    edges = [\r\n        (weight, start, to_node)\r\n        for to_node, weight in graph[start]\r\n    ]\r\n    heapq.heapify(edges)\r\n\r\n    mst = []\r\n    while edges:\r\n        weight, frm, to = heapq.heappop(edges)\r\n        if to not in visited:\r\n            visited.add(to)\r\n            mst.append((frm, to, weight))\r\n\r\n            for next_node, next_weight in graph[to]:\r\n                if next_node not in visited:\r\n                    heapq.heappush(edges, (next_weight, to, next_node))\r\n    return mst\r\n<\/pre>\n<p>If you define the <code class=\"\" data-line=\"\">graph<\/code> as adjacency lists (with nodes mapped to lists of <code class=\"\" data-line=\"\">(neighbor, weight)<\/code>), this gives the MST edges as <code class=\"\" data-line=\"\">mst<\/code>. This is a common efficient way to implement Prim\u2019s algorithm using a priority queue (heap) \u2014 which improves performance, especially for sparse graphs.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-20094 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python.webp\" alt=\"\" width=\"538\" height=\"303\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python.webp 1280w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python-300x169.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python-1024x576.webp 1024w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python-768x432.webp 768w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python-380x214.webp 380w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python-800x450.webp 800w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-algorithm-python-1160x653.webp 1160w\" sizes=\"(max-width: 538px) 100vw, 538px\" \/><\/p>\n<h3>Let\u2019s take a sample weighted graph:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"lua\">    (2)\r\nA ------- B\r\n| \\       |\r\n4   3     5\r\n|     \\   |\r\nC ------- D\r\n     (6)\r\n<\/pre>\n<p><strong>Step-by-step using Prim\u2019s:<\/strong><\/p>\n<table>\n<thead>\n<tr>\n<th>Step<\/th>\n<th>Chosen Edge<\/th>\n<th>Weight<\/th>\n<th>MST Nodes<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1<\/td>\n<td>Start at A<\/td>\n<td>\u2014<\/td>\n<td>A<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>A \u2192 B<\/td>\n<td>2<\/td>\n<td>A, B<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>A \u2192 C<\/td>\n<td>4<\/td>\n<td>A, B, C<\/td>\n<\/tr>\n<tr>\n<td>4<\/td>\n<td>B \u2192 D<\/td>\n<td>5<\/td>\n<td>A, B, C, D<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3 data-start=\"3812\" data-end=\"3851\"><strong data-start=\"3816\" data-end=\"3851\">Total MST Cost = 2 + 4 + 5 = 11<\/strong><\/h3>\n<p data-start=\"3853\" data-end=\"3888\">No cycles.<br data-start=\"3863\" data-end=\"3866\" \/>All nodes connected.<\/p>\n<h2 data-start=\"3853\" data-end=\"3888\">Prim\u2019s Algorithm vs Kruskal\u2019s Algorithm<\/h2>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-20090 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prim-kruskal.webp\" alt=\"\" width=\"530\" height=\"318\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prim-kruskal.webp 750w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prim-kruskal-300x180.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prim-kruskal-380x228.webp 380w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prim-kruskal-560x336.webp 560w\" sizes=\"(max-width: 530px) 100vw, 530px\" \/><\/p>\n<table>\n<thead>\n<tr>\n<th>Feature<\/th>\n<th>Prim\u2019s<\/th>\n<th>Kruskal\u2019s<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Approach<\/td>\n<td>Grows from a starting node<\/td>\n<td>Sorts &amp; connects edges globally<\/td>\n<\/tr>\n<tr>\n<td>Works well with<\/td>\n<td>Dense graphs<\/td>\n<td>Sparse graphs<\/td>\n<\/tr>\n<tr>\n<td>Data structure support<\/td>\n<td>Priority Queue (Binary Heap)<\/td>\n<td>Disjoint Set (Union-Find)<\/td>\n<\/tr>\n<tr>\n<td>Initial choice<\/td>\n<td>Random starting vertex required<\/td>\n<td>No starting vertex<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2 data-start=\"4529\" data-end=\"4578\">Real World Applications of Prim\u2019s Algorithm<\/h2>\n<ul data-start=\"4580\" data-end=\"4808\">\n<li data-start=\"4580\" data-end=\"4604\">\n<p data-start=\"4582\" data-end=\"4604\">\ud83d\udef0 Network Routing<\/p>\n<\/li>\n<li data-start=\"4605\" data-end=\"4639\">\n<p data-start=\"4607\" data-end=\"4639\">\ud83d\udee3 Road and Railway Planning<\/p>\n<\/li>\n<li data-start=\"4640\" data-end=\"4679\">\n<p data-start=\"4642\" data-end=\"4679\">\ud83c\udf10 Internet backbone cable design<\/p>\n<\/li>\n<li data-start=\"4680\" data-end=\"4722\">\n<p data-start=\"4682\" data-end=\"4722\">\ud83d\udce1 Telecommunication tower placement<\/p>\n<\/li>\n<li data-start=\"4723\" data-end=\"4765\">\n<p data-start=\"4725\" data-end=\"4765\">\ud83e\udd16 AI and Robotics path optimization<\/p>\n<\/li>\n<li data-start=\"4766\" data-end=\"4808\">\n<p data-start=\"4768\" data-end=\"4808\">\ud83d\udd78 Graph-based clustering algorithms<\/p>\n<\/li>\n<\/ul>\n<h2 data-start=\"4918\" data-end=\"4971\">When \/ Why Use Prim\u2019s Algorithm<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-20093 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims.webp\" alt=\"\" width=\"446\" height=\"251\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims.webp 560w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-300x169.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/11\/prims-380x214.webp 380w\" sizes=\"(max-width: 446px) 100vw, 446px\" \/><\/p>\n<p data-start=\"4973\" data-end=\"5044\">Prim\u2019s algorithm (or its variants) appears in many practical scenarios:<\/p>\n<ul data-start=\"5046\" data-end=\"5503\">\n<li data-start=\"5046\" data-end=\"5204\">\n<p data-start=\"5048\" data-end=\"5204\">Designing networks (like fiber-optic cables, electricity grids, transportation, roads) \u2014 whenever you need to connect many points with minimal \u201ccost\u201d.<\/p>\n<\/li>\n<li data-start=\"5205\" data-end=\"5304\">\n<p data-start=\"5207\" data-end=\"5304\">In <strong data-start=\"5210\" data-end=\"5231\">computer networks<\/strong> \/ <strong data-start=\"5234\" data-end=\"5263\">graph-based optimizations<\/strong> \u2014 for efficient routing or clustering.<\/p>\n<\/li>\n<li data-start=\"5305\" data-end=\"5503\">\n<p data-start=\"5307\" data-end=\"5503\">In <strong data-start=\"5310\" data-end=\"5332\">image segmentation<\/strong>, <strong data-start=\"5334\" data-end=\"5352\">bioinformatics<\/strong>, or <strong data-start=\"5357\" data-end=\"5384\">spanning-tree protocols<\/strong> \u2014 anywhere MST logic helps reduce redundancy while maintaining connectivity.<\/p>\n<\/li>\n<\/ul>\n<p data-start=\"5505\" data-end=\"5653\">Basically, when the problem can be modeled as \u201cconnect all points, minimize total connection cost, avoid loops\u201d \u2014 Prim\u2019s algorithm is your friend.<\/p>\n<h2 data-start=\"5660\" data-end=\"5675\">Conclusion<\/h2>\n<p data-start=\"5677\" data-end=\"5847\">I hope this article helped you understand Prim\u2019s algorithm in a clear, beginner-friendly way \u2014 just like I wished someone had explained to me when I first saw MSTs.<\/p>\n<p data-start=\"5849\" data-end=\"6019\">Whether you\u2019re preparing for coding interviews, studying graph theory, or building real-world networks \u2014 this greedy but powerful algorithm gives you a dependable tool<\/p>\n<p data-start=\"5849\" data-end=\"6019\">Want Learn More?, Kaashiv Infotech Offers <a href=\"https:\/\/www.kaashivinfotech.com\/cloud-computing-course-in-chennai\/\">Cloud Computing Course<\/a>,\u00a0<a href=\"https:\/\/www.kaashivinfotech.com\/cyber-security-course-in-chennai-2\/\">Cyber Security Course<\/a>,\u00a0<a href=\"https:\/\/www.kaashivinfotech.com\/networking-training-in-chennai\/\">Networking Course<\/a> &amp; More, Visit Our Website <a href=\"https:\/\/www.kaashivinfotech.com\/\">www.kaashivinfotech.com<\/a>.<\/p>\n<h2 data-start=\"5849\" data-end=\"6019\">Related Reads:<\/h2>\n<ul>\n<li>\n<p class=\"entry-title\"><a href=\"https:\/\/www.kaashivinfotech.com\/blog\/greedy-algorithm-guide-2025\/\">Greedy Algorithm: Guide, Examples &amp; vs Dynamic Programming<\/a><\/p>\n<\/li>\n<li>\n<p class=\"entry-title\"><a href=\"https:\/\/www.kaashivinfotech.com\/blog\/virtualization-in-cloud-computing\/\">Virtualization in Cloud Computing and Types: My Honest Take in 2025<\/a><\/p>\n<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>What Is Prim\u2019s Algorithm? Prim\u2019s Algorithm is a greedy algorithm used to find a Minimum Spanning Tree (MST) from a weighted, connected, undirected graph. Yep \u2014 that\u2019s the one-line exam-ready answer. But let\u2019s make it human. Think of Prims like building a road network between multiple cities using the minimum cost possible, without creating loops. [&hellip;]<\/p>\n","protected":false},"author":8,"featured_media":20092,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[220],"tags":[10644,10638,10642,10639,10641,10640,10643,10637],"class_list":["post-20088","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology","tag-kruskals-algorithm","tag-prims-algorithm-gfg-practice","tag-prims-algorithm-in-daa","tag-prims-algorithm-leetcode","tag-prims-algorithm-practice","tag-prims-algorithm-time-complexity","tag-prims-algorithm-vs-kruskal","tag-prims-algorithm-wikipedia"],"_links":{"self":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/20088","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/comments?post=20088"}],"version-history":[{"count":0,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/20088\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/media\/20092"}],"wp:attachment":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/media?parent=20088"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/categories?post=20088"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/tags?post=20088"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}