# Prim’s MST for Adjacency List Representation

It is similar to the previous algorithm. Here the only difference is, the Graph G(V, E) is represented by an adjacency list.

Time complexity adjacency list representation is O(E log V).

## Input and Output

Input:
The cost matrix:

Output:
Edge: A--B And Cost: 1
Edge: B--E And Cost: 2
Edge: A--C And Cost: 3
Edge: A--D And Cost: 4
Edge: E--F And Cost: 2
Edge: F--G And Cost: 3
Total Cost: 15

## Algorithm

prims(g: Graph, start)

Input −  The graph g and the seed vertex named ‘start’

Output − The Tree after adding edges.

Begin
create two set B, N
add the start node in B set.

for all vertices u in graph g do
add u in the set N
done

while B ≠ N do
min := ∞
for all vertices u in graph g do
if u is in the set B then
for all vertices v which are adjacent with u do
if v is in (N – B) then
if min > cost of uv edge then
min := cost of uv edge
parent := u
node := v
done
done

insert node in the B set
add the edge starting from parent to node in the tree
done

return the tree
End

## Example

#include<iostream>
#include<list>
#include<set>
using namespace std;

typedef struct nodes {
int dest;
int cost;
}node;

class Graph {
int n;
private:
void showList(int src, list<node> lt) {
list<node> :: iterator i;
node tempNode;

for(i = lt.begin(); i != lt.end(); i++) {
tempNode = *i;
cout << "(" << src << ")---("<<tempNode.dest << "|"<<tempNode.cost<<") ";
}
cout << endl;
}

public:
Graph() {
n = 0;
}

Graph(int nodeCount) {
n = nodeCount;
}

void addEdge(int source, int dest, int cost) {
node newNode;
newNode.dest = dest;
newNode.cost = cost;
}

void displayEdges() {
for(int i = 0; i<n; i++) {
showList(i, tempList);
}
}

friend Graph primsMST(Graph g, int start);
};

set<int> difference(set<int> first, set<int> second) {
set<int> :: iterator it;
set<int> res;

for(it = first.begin(); it != first.end(); it++) {
if(second.find(*it) == second.end())
res.insert(*it);    //add those item which are not in the second list
}

return res;    //the set (first-second)
}

Graph primsMST(Graph g, int start) {
int n = g.n;
set<int> B, N, diff;
Graph tree(n);        //make tree with same node as graph
B.insert(start);     //insert start node in the B set

for(int u = 0; u<n; u++) {
N.insert(u); //add all vertices in the N set
}

while(B != N) {
int min = 9999;             //set as infinity
int v, par;
diff = difference(N, B);    //find the set N - B

for(int u = 0; u < n; u++) {
if(B.find(u) != B.end()) {
list<node>::iterator it;
if(diff.find(it->dest) != diff.end()) {
if(min > it->cost) {
min = it->cost;    //update cost
par = u;
v = it->dest;
}
}
}
}
}

B.insert(v);
}
return tree;
}

main() {
Graph g(7), tree(7);

tree = primsMST(g, 0);
tree.displayEdges();
}

## Output

Edge: A--B And Cost: 1
Edge: B--E And Cost: 2
Edge: A--C And Cost: 3
Edge: A--D And Cost: 4
Edge: E--F And Cost: 2
Edge: F--G And Cost: 3
Total Cost: 15
Sharon Christine

An investment in knowledge pays the best interest