Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation) - GeeksforGeeks

11 Aug, 2021
We have discussed Prim’s algorithm and its implementation for adjacency matrix representation of graphs. As discussed in the previous post, in Prim’s algorithm, two sets are maintained, one set contains list of vertices already included in MST, other set contains vertices not yet included. In every iteration, we consider the minimum weight edge among the edges that connect the two sets.The implementation discussed in previous post uses two arrays to find minimum weight edge that connects the two sets. Here we use one inMST[V]. The value of MST[i] is going to be true if vertex i is included in the MST. In every pass, we consider only those edges such that one vertex of the edge is included in MST and other is not. After we pick an edge, we mark both vertices as included in MST.  
C++
Java
Python3
C#
Javascript
// A simple C++ implementation to find minimum// spanning tree for adjacency representation.#include <bits/stdc++.h>using namespace std;#define V 5 // Returns true if edge u-v is a valid edge to be// include in MST. An edge is valid if one end is// already included in MST and other is not in MST.bool isValidEdge(int u, int v, vector<bool> inMST){   if (u == v)       return false;   if (inMST[u] == false && inMST[v] == false)        return false;   else if (inMST[u] == true && inMST[v] == true)        return false;   return true;} void primMST(int cost[][V]){     vector<bool> inMST(V, false);     // Include first vertex in MST    inMST[0] = true;     // Keep adding edges while number of included    // edges does not become V-1.    int edge_count = 0, mincost = 0;    while (edge_count < V - 1) {         // Find minimum weight valid edge.         int min = INT_MAX, a = -1, b = -1;        for (int i = 0; i < V; i++) {            for (int j = 0; j < V; j++) {                              if (cost[i][j] < min) {                    if (isValidEdge(i, j, inMST)) {                        min = cost[i][j];                        a = i;                        b = j;                    }                }            }        }        if (a != -1 && b != -1) {            printf("Edge %d:(%d, %d) cost: %d \n",                         edge_count++, a, b, min);            mincost = mincost + min;            inMST[b] = inMST[a] = true;        }    }    printf("\n Minimum cost= %d \n", mincost);} // driver program to test above functionint main(){    /* Let us create the following graph          2    3      (0)--(1)--(2)       |   / \   |      6| 8/   \5 |7       | /     \ |      (3)-------(4)            9          */    int cost[][V] = {        { INT_MAX, 2, INT_MAX, 6, INT_MAX },        { 2, INT_MAX, 3, 8, 5 },        { INT_MAX, 3, INT_MAX, INT_MAX, 7 },        { 6, 8, INT_MAX, INT_MAX, 9 },        { INT_MAX, 5, 7, 9, INT_MAX },    };     // Print the solution    primMST(cost);     return 0;}
// A simple Java implementation to find minimum// spanning tree for adjacency representation.import java.util.*; class GFG{ static int V = 5;static int INT_MAX = Integer.MAX_VALUE; // Returns true if edge u-v is a valid edge to be// include in MST. An edge is valid if one end is// already included in MST and other is not in MST.static boolean isValidEdge(int u, int v,                           boolean[] inMST){    if (u == v)        return false;    if (inMST[u] == false && inMST[v] == false)        return false;    else if (inMST[u] == true && inMST[v] == true)        return false;    return true;} static void primMST(int cost[][]){    boolean []inMST = new boolean[V];     // Include first vertex in MST    inMST[0] = true;     // Keep adding edges while number of included    // edges does not become V-1.    int edge_count = 0, mincost = 0;    while (edge_count < V - 1)    {         // Find minimum weight valid edge.        int min = INT_MAX, a = -1, b = -1;        for (int i = 0; i < V; i++)        {            for (int j = 0; j < V; j++)            {                            if (cost[i][j] < min)                {                    if (isValidEdge(i, j, inMST))                    {                        min = cost[i][j];                        a = i;                        b = j;                    }                }            }        }                 if (a != -1 && b != -1)        {            System.out.printf("Edge %d:(%d, %d) cost: %d \n",                                    edge_count++, a, b, min);            mincost = mincost + min;            inMST[b] = inMST[a] = true;        }    }    System.out.printf("\n Minimum cost = %d \n", mincost);} // Driver Codepublic static void main(String[] args){    /* Let us create the following graph        2 3    (0)--(1)--(2)    | / \ |    6| 8/ \5 |7    | /     \ |    (3)-------(4)            9         */    int cost[][] = {{ INT_MAX, 2, INT_MAX, 6, INT_MAX },                    { 2, INT_MAX, 3, 8, 5 },                    { INT_MAX, 3, INT_MAX, INT_MAX, 7 },                    { 6, 8, INT_MAX, INT_MAX, 9 },                    { INT_MAX, 5, 7, 9, INT_MAX }};     // Print the solution    primMST(cost);}} // This code is contributed by Rajput-Ji
# Python3 implementation to find minimum# spanning tree for adjacency representation.from sys import maxsizeINT_MAX = maxsizeV = 5 # Returns true if edge u-v is a valid edge to be# include in MST. An edge is valid if one end is# already included in MST and other is not in MST.def isValidEdge(u, v, inMST):    if u == v:        return False    if inMST[u] == False and inMST[v] == False:        return False    elif inMST[u] == True and inMST[v] == True:        return False    return True def primMST(cost):    inMST = [False] * V     # Include first vertex in MST    inMST[0] = True     # Keep adding edges while number of included    # edges does not become V-1.    edge_count = 0    mincost = 0    while edge_count < V - 1:         # Find minimum weight valid edge.        minn = INT_MAX        a = -1        b = -1        for i in range(V):            for j in range(V):                if cost[i][j] < minn:                    if isValidEdge(i, j, inMST):                        minn = cost[i][j]                        a = i                        b = j         if a != -1 and b != -1:            print("Edge %d: (%d, %d) cost: %d" %                 (edge_count, a, b, minn))            edge_count += 1            mincost += minn            inMST[b] = inMST[a] = True     print("Minimum cost = %d" % mincost) # Driver Codeif __name__ == "__main__":    ''' Let us create the following graph        2 3    (0)--(1)--(2)    | / \ |    6| 8/ \5 |7    | /     \ |    (3)-------(4)            9         '''     cost = [[INT_MAX, 2, INT_MAX, 6, INT_MAX],            [2, INT_MAX, 3, 8, 5],            [INT_MAX, 3, INT_MAX, INT_MAX, 7],            [6, 8, INT_MAX, INT_MAX, 9],            [INT_MAX, 5, 7, 9, INT_MAX]]     # Print the solution    primMST(cost) # This code is contributed by# sanjeev2552
// A simple C# implementation to find minimum// spanning tree for adjacency representation.using System; class GFG{ static int V = 5;static int INT_MAX = int.MaxValue; // Returns true if edge u-v is a valid edge to be// include in MST. An edge is valid if one end is// already included in MST and other is not in MST.static bool isValidEdge(int u, int v,                        bool[] inMST){    if (u == v)        return false;    if (inMST[u] == false && inMST[v] == false)        return false;    else if (inMST[u] == true &&             inMST[v] == true)        return false;    return true;} static void primMST(int [,]cost){    bool []inMST = new bool[V];     // Include first vertex in MST    inMST[0] = true;     // Keep adding edges while number of    // included edges does not become V-1.    int edge_count = 0, mincost = 0;    while (edge_count < V - 1)    {         // Find minimum weight valid edge.        int min = INT_MAX, a = -1, b = -1;        for (int i = 0; i < V; i++)        {            for (int j = 0; j < V; j++)            {                        if (cost[i, j] < min)                {                    if (isValidEdge(i, j, inMST))                    {                        min = cost[i, j];                        a = i;                        b = j;                    }                }            }        }                 if (a != -1 && b != -1)        {            Console.Write("Edge {0}:({1}, {2}) cost: {3} \n",                                    edge_count++, a, b, min);            mincost = mincost + min;            inMST[b] = inMST[a] = true;        }    }    Console.Write("\n Minimum cost = {0} \n", mincost);} // Driver Codepublic static void Main(String[] args){    /* Let us create the following graph        2 3    (0)--(1)--(2)    | / \ |    6| 8/ \5 |7    | / \ |    (3)-------(4)            9     */    int [,]cost = {{ INT_MAX, 2, INT_MAX, 6, INT_MAX },                   { 2, INT_MAX, 3, 8, 5 },                   { INT_MAX, 3, INT_MAX, INT_MAX, 7 },                   { 6, 8, INT_MAX, INT_MAX, 9 },                   { INT_MAX, 5, 7, 9, INT_MAX }};     // Print the solution    primMST(cost);}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation to find minimum// spanning tree for adjacency representation. let V = 5;let let_MAX = Number.MAX_VALUE;   // Returns true if edge u-v is a valid edge to be// include in MST. An edge is valid if one end is// already included in MST and other is not in MST.function isValidEdge(u, v, inMST){    if (u == v)        return false;    if (inMST[u] == false && inMST[v] == false)        return false;    else if (inMST[u] == true && inMST[v] == true)        return false;    return true;}   function primMST(cost){    let inMST = Array(V).fill(false);       // Include first vertex in MST    inMST[0] = true;       // Keep adding edges while number of included    // edges does not become V-1.    let edge_count = 0, mincost = 0;    while (edge_count < V - 1)    {           // Find minimum weight valid edge.        let min = let_MAX, a = -1, b = -1;        for (let i = 0; i < V; i++)        {            for (let j = 0; j < V; j++)            {                            if (cost[i][j] < min)                {                    if (isValidEdge(i, j, inMST))                    {                        min = cost[i][j];                        a = i;                        b = j;                    }                }            }        }                   if (a != -1 && b != -1)        {            document.write("Edge " +            edge_count++ + ": (" +  a +"," + b +            ") " + "cost: " + min + "<br/>");            mincost = mincost + min;            inMST[b] = inMST[a] = true;        }    }     document.write("<br>");     document.write("  ");     document.write("Minimum cost = " + mincost);} // driver code       /* Let us create the following graph        2 3    (0)--(1)--(2)    | / \ |    6| 8/ \5 |7    | /     \ |    (3)-------(4)            9         */    let cost = [[ let_MAX, 2, let_MAX, 6, let_MAX ],                    [ 2, let_MAX, 3, 8, 5 ],                    [ let_MAX, 3, let_MAX, let_MAX, 7 ],                    [ 6, 8, let_MAX, let_MAX, 9 ],                    [ let_MAX, 5, 7, 9, let_MAX ]];       // Print the solution    primMST(cost);   </script>
Edge 0:(0, 1) cost: 2 
Edge 1:(1, 2) cost: 3 
Edge 2:(1, 4) cost: 5 
Edge 3:(0, 3) cost: 6 

 Minimum cost= 16
 
Time Complexity: O(V3)Note that time complexity of previous approach that uses adjacency matrix is O(V2) and time complexity of the adjacency list representation implementation is O((E+V)LogV).Auxiliary Space: O(E + V) 
Rajput-Ji
princiraj1992
sanjeev2552
chinmoy1997pal
pankajsharmagfg
Prim's Algorithm.MST
Algorithms
C++ Programs
Graph
Greedy
Matrix
Greedy
Matrix
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL