You are on page 1of 18

CHAPTER 1

INTRODUCTION

1.1 INTRODUCTION

Prim’s algorithm is a Greedy algorithm. This algorithm always starts with a single node
and moves through several adjacent nodes, in order to explore all of the connected edges
along the way. The algorithm starts with an empty spanning tree. The idea is to maintain
two sets of vertices. The first set contains the vertices already included in the MST, and the
other set contains the vertices not yet included. At every step, it considers all the edges that
connect the two sets and picks the minimum weight edge from these edges. After picking
the edge, it moves the other endpoint of the edge to the set containing MST. A group of
edges that connects two sets of vertices in a graph is called cut in graph theory. So, at every
step of Prim’s algorithm, find a cut, pick the minimum weight edge from the cut, and include
this vertex in MST Set (the set that contains already included vertices).

1
CHAPTER 2

DESCRIPTION

2.1 Prim's Algorithm :-

Prim’s algorithm is a minimum spanning tree algorithm which helps to find out the
edges of the graph to form the tree including every node with the minimum sum of weights to form
the minimum spanning tree. Prim’s algorithm starts with the single source node and later explore
all the adjacent nodes of the source node with all the connecting edges. While we are exploring
the graphs, we will choose the edges with the minimum weight and those which cannot cause the
cycles in the graph.

2.2 Prim's Algorithm for Minimum Spanning Tree :-

Prim's algorithm basically follows the greedy algorithm approach to find the optimal
solution. To find the minimum spanning tree using prim's algorithm, we will choose a source node
and keep adding the edges with the lowest weight.

The working of Prim’s algorithm can be described by using the following steps:

Step 1: Determine an arbitrary vertex as the starting vertex of the MST.


Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as
fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit.

2
2.3 Time Complexity :-

The running time for prim’s algorithm is O(VlogV + ElogV) which is equal to
O(ElogV) because every insertion of a node in the solution takes logarithmic time. Here, E is the
number of edges and V is the number of vertices/nodes. However, we can improve the running
time complexity to O(E + logV) of prim’s algorithm using Fibonacci Heaps.

2.4 Applications :-

• Prim’s algorithm is used in network design


• It is used in network cycles and rail tracks connecting all the cities
• Prim’s algorithm is used in laying cables of electrical wiring
• Prim’s algorithm is used in irrigation channels and placing microwave towers
• It is used in cluster analysis
• Prim’s algorithm is used in gaming development and cognitive science
• Pathfinding algorithms in artificial intelligence and traveling salesman problems make
use of prim’s algorithm.

3
CHAPTER 3

ABOUT THE PROJECT

Prim’s Algorithm is an algorithm that takes a weighted undirected graph as an input


and outputs its Minimum Spanning Tres(MST).At every step,it selects an open edge that has the
minimum weight.

The starting vertex of the algorithm will be choosen arbitrarily,because the first
iteration of the main loop of the algorithm will have a set of vertices in Q that all have equal
weights,and the algorithm will automatically start a new tree in F when it completes a spanning
tree of each connected component of the input graph.The algorithm may be modified to start with
any particular vertex s by setting C[s] to be a number smaller than the other values of C(for
instance,zero),and it may be modified to only find a single spanning tree rather than an entire
spanning forest(matching more closely the informal description) by stoping whenever it
encounters another vertex flagged as having no associated edges.

Different variations of the algorithm differ from each other in how the set Q is
implemented as a simple linked list or array of vertices,or as a more complicated priority queue
data structure .This choice leads to differences in the time complexity of the algorithm.Prim,s
algorithm visualization can be used as a repository for the concrete and abstract proof objects.

The algorithm starts with an empty spanning tree with two set of vertices.The
implementation of Prim’s algorithm begins with the creation of graph structure.This adjacency
matrix will store weights and edges between different nodes of a graph

4
CHAPTER 4

SYSTEM ANALYSIS

Prim’s algorithm use greedy approach to find the minimum spanning tree. In Prim’s
algorithm we grow the spanning tree from a starting position. Unlike an edge in Kruskal’s, we
add vertex to the growing spanning tree in Prim’s.

4.1 ALGORITHM STEPS:

• Maintain 2 disjoint sets of vertices. One containing vertices that are in the growing
spanning tree and other that are not in the growing spanning tree.
• Select the cheapest vertex that is connected to the growing spanning tree and is not in the
growing spanning tree and add it into the growing spanning tree. This can be done using
Priority Queues. Insert the vertices, that are connected to the growing spanning tree, into
the Priority Queue.
• Check for cycles. To do that mark the nodes which have been already selected and insert
only those not in the Priority Queue that are not marked.

5
CHAPTER 5

SYSTEM IMPLEMENTATION

5.1 EXAMPLE DIAGRAM

1
B C
3
4 4 6

A 5 5
F D

6 2 8

5.2 SOLUTION DIAGRAM

1
B C

3 4

F D
5
2

6
CHAPTER 6
ABOUT THE CODE

Prim's algorithm finds the minimum spanning tree (MST) for a weighted graph. That is, the
set of edges that connects every node in the graph while minimizing total edge weight.

Computing a graph's MST is, on its surface, a pretty difficult problem to solve. If you were handed
a graph on paper with hundreds of nodes and edges, finding the MST without knowing an
algorithm seems like it could easily take months (even knowing an algorithm, doing it by hand
would be a daunting task).

But Prim's algorithm is a great example of a problem that becomes much easier to understand and
solve with the right approach and data structures. It combines a number of interesting challenges
and algorithmic approaches - namely sorting, searching, greediness, and efficiently processing
items by priority. As a bonus, it's a delight to watch in action, to see the algorithm start in the
middle of a jumbled mess of edges and nodes and slowly conquer the graph.

To import priority queue use matplotlib animation.

To make the visualization reasonable, we'll create a graph with 25 nodes and 150 edges. Each node
is represented with a number [0,25) and each edge is given a random weight [0,1].

We start by creating a graph and adding edges between consecutive nodes so that all nodes in the
graph are connected. That is, we connect nodes (0,1), (1,2), (2,3), etc. so that we aren't left with
any unconnected nodes. Then, we create another 125 edges between random nodes. Each edge is
given a random weight between 0 and 1.

For the last bit of set-up, we need to create three sets to store:
● All edges in the graph
● The edges of the graph in the MST
● The nodes of the graph in the MST

7
We initialize (2) and (3) to be empty and Prim's algorithm will add new edges and nodes until (3)
contains all nodes in the graph.

Edges are represented as tuples that hold the two nodes connected by the edge. Because the edges
are undirected, an edge between nodes 1 and 5 could be represented as (1, 5) or (5, 1). To simplify
comparing edges between data structures, we'll always store them in sorted order (in this case, (1,
5)).

Finally, we're ready to implement Prim's algorithm. The algorithm works on the following
principle - if you have a set of nodes and edges that you know are in the MST, then the edge with
minimum weight that connects a node in the MST to a node not already in the MST is guaranteed
to be in the MST.
Take a graph with four nodes where each node is connected with the following weights.

Let's say we start at Node 1 (it doesn't matter which node we start with). The edge with minimum
weight connected to Node 1 is (1,2) so that must be in the MST.

Now, we want to know the edge with minimum weight that takes us from a node in the MST (1 or
2) to a node that is not in the MST (3 or 4). In our example, it's easy to see that (1,3) has the next
smallest weight and, after that, (1,4) which connects every node. The final MST is (1,2), (1,3), and
(1,4).

Our example is simple, but in large graphs with many nodes and edges, the challenge is to
efficiently find the edge with the lowest weight. For this, Prim's algorithm uses a minimum priority
queue which maintains the queue such that the next element returned always contains the smallest
weight.

PriorityQueue is a minimum priority queue that takes a tuple in the form (priority_value, element).
In our case, priority_value is the edge's weight and element is the tuple representing the edge. For
example, the edge (1,2) with a weight of 0.5 would be added to the priority queue with:
pqueue.put((0.5, (1, 2)))

8
The last step is to provide the functions to draw the graph and MST in matplotlib.
We'll use draw_networkx_nodes and draw_networkx_edges to draw three elements:
● All nodes in the graph
● The edges in the graph not in the MST, drawn in light green. This is computed by taking
the difference between the set of all edges in the graph and the edges in the MST.
● The edges in the graph in the MST, drawn in deep blue.
Finally we can able to see the animation.

9
CHAPTER 7
SYSTEM SPECIFICATIONS

7.1 SYSTEM REQUIREMENTS

7.1.1 SOFTWARE REQUIREMENTS

• WorkingSystem: Windows
• Technology: Python
• IDE: Python IDLE
• Python version: Python 3.10 64bit

7.1.2 HARDWARE REQUIREMENTS

• Equipment: Computer System


• Console: StandardWindowsKeyboard
• Mouse: TwoorThreeButtonMouse
• Screen: SVGA
• Speed: 1.1 GHz

7.2 SOFTWARE ENVIRONMENT

7.2.1 PYTHON TECHNOLOGY

Python has become one of the most popular programming languages in the world in
recent years. It's used in everything from machine learning to building websites and software
testing. It can be used by developers and non-developers alike.

Python, one of the most popular programming languages in the world, has created
everything from Netflix’s recommendation algorithm to the software that controls self-driving
cars. Python is a general-purpose language, which means it’s designed to be used in a range of

10
applications, including data science, software and web development, automation, and generally
getting stuff done.

Python is a computer programming language often used to build websites and


software, automate tasks, and conduct data analysis. Python is a general-purpose language,
meaning it can be used to create a variety of different programs and isn’t specialized for any
specific problems. This versatility, along with its beginner-friendliness, has made it one of the
most-used programming languages today. A survey conducted by industry analyst firm
RedMonk found that it was the second-most popular programming language among developers
in 2021

Python used for?

Python is commonly used for developing websites and software, task automation, data
analysis, and data visualization. Since it’s relatively easy to learn, Python has been adopted by
many non-programmers such as accountants and scientists, for a variety of everyday tasks, like
organizing finances.

“Writing programs is a very creative and rewarding activity,” says University of Michigan and
Coursera instructor Charles R Severance in his book Python for Everybody. “You can write
programs for many reasons, ranging from making your living to solving a difficult data analysis
problem to having fun to helping someone else solve a problem.”

What can you do with python? Some things include:

➢ Data analysis and machine learning


➢ Web development
➢ Automation or scripting
➢ Software testing and prototyping
➢ Everyday tasks

11
CHAPTER 8
SAMPLE CODING

from queue import PriorityQueue

from random import randint, uniform

import networkx as nx

from matplotlib import animation, rc

import matplotlib.pyplot as plt

rc('animation', html='html5')

NUM_NODES = 25

def random_node():

return randint(0, NUM_NODES-1)

def random_weight():

return uniform(0, 1)

graph = nx.Graph()

for i in range(1, NUM_NODES):

graph.add_edge(i-1, i, weight=random_weight())

for _ in range(NUM_NODES * 5):

graph.add_edge(

random_node(), random_node(), weight=random_weight()

pos = nx.random_layout(graph)

%%capture

all_edges = set(

12
tuple(sorted((n1, n2))) for n1, n2 in graph.edges()

edges_in_mst = set()

nodes_on_mst = set()

fig, ax = plt.subplots(figsize=(6,4))

def prims():

pqueue = PriorityQueue()

# Start at any random node and add all edges connected to this

# node to the priority queue.

start_node = random_node()

for neighbor in graph.neighbors(start_node):

edge_data = graph.get_edge_data(start_node, neighbor)

edge_weight = edge_data["weight"]

pqueue.put((edge_weight, (start_node, neighbor)))

# Loop until all nodes are in the MST

while len(nodes_on_mst) < NUM_NODES:

# Get the edge with smallest weight from the priority queue

_, edge = pqueue.get(pqueue)

if edge[0] not in nodes_on_mst:

new_node = edge[0]

elif edge[1] not in nodes_on_mst:

new_node = edge[1]

else:

13
# If this edge connects two nodes that are already in the

# MST, then skip this and continue to the next edge in

# the priority queue.

continue

# Every time a new node is added to the priority queue, add

# all edges that it sits on to the priority queue.

for neighbor in graph.neighbors(new_node):

edge_data = graph.get_edge_data(new_node, neighbor)

edge_weight = edge_data["weight"]

pqueue.put((edge_weight, (new_node, neighbor)))

# Add this edge to the MST.

edges_in_mst.add(tuple(sorted(edge)))

nodes_on_mst.add(new_node)

# Yield edges in the MST to plot.

yield edges_in_mst

def update(mst_edges):

ax.clear()

nx.draw_networkx_nodes(graph, pos, node_size=25, ax=ax)

nx.draw_networkx_edges(

graph, pos, edgelist=all_edges-mst_edges, alpha=0.1,

edge_color='g', width=1, ax=ax

nx.draw_networkx_edges(

14
graph, pos, edgelist=mst_edges, alpha=1.0,

edge_color='b', width=1, ax=ax

def do_nothing():

# FuncAnimation requires an initialization function. We don't

# do any initialization, so we provide a no-op function.

Pass

ani = animation.FuncAnimation(

fig,

update,

init_func=do_nothing,

frames=prims,

interval=500,

ani

15
CHAPTER 9

SAMPLE OUTPUT

16
CHAPTER 10
CONCLUSION

In this Project the prims algorithm visualization was implemented successfully. Prim’s
algorithm has the priority that the edges in the set T, which contains the edges of the minimum
spanning tree when the algorithm proceeds step by step, always form a single tree. That is, at
each step , there is only one connected component. Prim’s algorithm is a great example of a
problem that becomes much easier to understand and solve with the right approach and data
structures. It combines a number of interesting challenges and algorithmic approaches –
namely sorting , searching , greediness , and efficiently processing items by priority. As a
bonus, it’s a delight to watch in action, to see the algorithm start in the middle of a jumbled
mess of edges and nodes and slowly conquer the graph.

17
CHAPTER 11
REFERENCES

➢ https://en.wikipedia.org/wiki/Prim%27s_algorithm
➢ https://www.oxfordreference.com/view/10.1093/oi/authority.20110803100345172
➢ https://www.programiz.com/dsa/prim-algorithm
➢ https://www.sciencedirect.com/topics/computer-science/prim-algorithm
➢ https://www.baeldung.com/cs/prim-algorithm
➢ https://wcipeg.com/wiki/Prim%27s_algorithm

18

You might also like