Professional Documents
Culture Documents
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
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.
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:
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 :-
3
CHAPTER 3
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.
• 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
1
B C
3
4 4 6
A 5 5
F D
6 2 8
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 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
• WorkingSystem: Windows
• Technology: Python
• IDE: Python IDLE
• Python version: Python 3.10 64bit
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 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.”
11
CHAPTER 8
SAMPLE CODING
import networkx as nx
rc('animation', html='html5')
NUM_NODES = 25
def random_node():
def random_weight():
return uniform(0, 1)
graph = nx.Graph()
graph.add_edge(i-1, i, weight=random_weight())
graph.add_edge(
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
start_node = random_node()
edge_weight = edge_data["weight"]
# Get the edge with smallest weight from the priority queue
_, edge = pqueue.get(pqueue)
new_node = edge[0]
new_node = edge[1]
else:
13
# If this edge connects two nodes that are already in the
continue
edge_weight = edge_data["weight"]
edges_in_mst.add(tuple(sorted(edge)))
nodes_on_mst.add(new_node)
yield edges_in_mst
def update(mst_edges):
ax.clear()
nx.draw_networkx_edges(
nx.draw_networkx_edges(
14
graph, pos, edgelist=mst_edges, alpha=1.0,
def do_nothing():
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