You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/algorithms/MST Prim/MST Prim.md
+24-22Lines changed: 24 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,35 +1,37 @@
1
1
---
2
-
jupyter:
3
-
jupytext:
4
-
text_representation:
5
-
extension: .md
6
-
format_name: markdown
7
-
format_version: '1.3'
8
-
jupytext_version: 1.13.8
9
-
kernelspec:
10
-
display_name: Python 3
11
-
language: python
12
-
name: python3
2
+
jupytext:
3
+
text_representation:
4
+
extension: .md
5
+
format_name: myst
6
+
format_version: 0.13
7
+
jupytext_version: 1.13.8
8
+
kernelspec:
9
+
display_name: Python 3
10
+
language: python
11
+
name: python3
13
12
---
14
13
15
14
# Minimum Spanning Tree using Prim's Algorithm
16
15
16
+
+++
17
17
18
18
We all have travelled by road from one city to another. But, ever wondered how they decided where to create the route and what path to choose? If one will get the job to connect 5 cities via road, then, the naive approach will be to start connecting from one city and continue doing that until one covers all destinations. But, that's not the optimal solution, not only one should cover all nodes but also at the lowest cost possible (minimum length of the road) and for that <b>Minimum Spanning Trees</b> are constructed using Prim's and Kruskal's algorithm.
19
19
20
20
When each and every node of a graph is connected to each other without forming any cycle, it is known as the <b>Spanning Tree.</b> A graph $G$ having $n$ nodes will have spanning trees with $n$ nodes and $n-1$ edges. Thus, as its name indicates, Minimum Spanning Tree is the tree with the shortest possible distance covered among all other spanning trees.<br> Let's look at the following example to understand this better.
21
21
22
+
+++
22
23
23
24
## Minimum Spanning Tree Problem
24
25
26
+
+++
25
27
26
28
Suppose there are 5 cities (A, B, C, D and E) that needs to be connected via road. Now, there can be more than one path connecting one city to another but our goal is to find the one having the shortest distance.
27
29
28
30
<b>ASSUMPTION</b>: Distance taken is imaginary.
29
31
30
32
The following graph depicts our situation in this case.
Now, in order to find the minimum spanning tree, this notepad will cover the Prim's algorithm.
83
84
Let's understand it in detail.
84
85
86
+
+++
85
87
86
88
## Prim's Algorithm
87
89
Prim's algorithm uses greedy approach to find the minimum spanning tree.That means, in each iteration it finds an edge which has the minimum weight and add it to the growing spanning tree.
@@ -95,13 +97,14 @@ The time complexity of the Prim’s Algorithm is $O((V+E) \text{ log} V)$ becau
95
97
4. Repeat steps 2 and 3 until all nodes are covered.
96
98
5. The final graph will represent the Minimum Spanning Tree
97
99
100
+
+++
98
101
99
102
### Example solution
100
103
Let's get back to the example and find its minimum spanning tree using Prim's algorithm. Before moving forward, here are a few notations that one should remember:
101
104
- Red nodes represent unvisited vertices while green nodes represent visited vertices.
102
105
- Edges of minimum spanning tree are represented in purple color.
103
106
104
-
```python
107
+
```{code-cell} ipython3
105
108
# converting graph to dictionary
106
109
road_list = roads._adj
107
110
@@ -115,7 +118,7 @@ inf = 1 + max([w['weight'] for u in road_list.keys() for (v,w) in road_list[u].i
115
118
### Step 1
116
119
Suppose the road construction starts from city A, so A is the source node. The distance of other cities is assumed to be unknown, so all other visited vertices are marked as 'not visited' and the distance as infinite (which equals 8 in this case).
117
120
118
-
```python
121
+
```{code-cell} ipython3
119
122
# assigning infinite distance to all nodes and marking all nodes as not visited
120
123
for v in road_list.keys():
121
124
(visited[v], distance[v]) = (False, inf) # false indicates not visited
@@ -169,7 +172,7 @@ Here, the following nodes will get updated:
After updating the distance in the previous step, it's time to find the next node with the minimum distance. To do this, iterate across the neighbours of the visited nodes and find the node with the minimum distance. Then update its distance and mark it as visited.
210
212
211
-
```python
213
+
```{code-cell} ipython3
212
214
# initialising the required dictionaries for plotting graphs
213
215
visited_list = []
214
216
distance_list = []
@@ -238,7 +240,6 @@ for i in road_list.keys():
238
240
if not visited[v]:
239
241
distance[v] = min(distance[v], d)
240
242
distance_list.append(distance.copy())
241
-
242
243
```
243
244
244
245
Let's understand each iteration and plot the graph!
@@ -265,7 +266,7 @@ Among the last 2 nodes, E has the minimum distance of 3 units. So, E will get ad
265
266
<b>Figure 4</b><br>
266
267
The final node D, with a distance of 2 units, got connected to the minimum spanning tree. This figure illustrates the final Minimum Spanning Tree of the example.
267
268
268
-
```python
269
+
```{code-cell} ipython3
269
270
fig, axes = plt.subplots(2, 2, figsize=(15,15))
270
271
c=0
271
272
for v,d,ax,edges in zip(visited_list,distance_list,axes.ravel(), edge_list):
@@ -315,7 +316,7 @@ for v,d,ax,edges in zip(visited_list,distance_list,axes.ravel(), edge_list):
315
316
### Step 5
316
317
The final output of the program is stored as a list of tuples in `TreeEdges` as shown below.
317
318
318
-
```python
319
+
```{code-cell} ipython3
319
320
print(TreeEdges)
320
321
```
321
322
@@ -325,7 +326,7 @@ The above code is a basic implementation of Prim's algorithm with the time compl
325
326
NetworkX provides various [Tree](https://networkx.org/documentation/stable/reference/algorithms/tree.html#) functions to perform difficult operations, and [minimum_spanning_tree()](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.tree.mst.minimum_spanning_tree.html#networkx.algorithms.tree.mst.minimum_spanning_tree) is one of them. Not only this, you can also find the maximum spanning tree with the help of the [maximum_spanning_tree()](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.tree.mst.maximum_spanning_tree.html#networkx.algorithms.tree.mst.maximum_spanning_tree) function.<br>
326
327
The following code uses NetworkX function and gives us the same output as our code.
There are many other similar applications present in this world. Whenever there's a need to find a cost-effective method to connect nodes (it can be anything), there's a high chance of Prim's algorithm playing its role in the solution.
342
343
344
+
+++
343
345
344
346
## Reference
345
347
R. C. Prim "Shortest connection networks and some generalizations." The bell system technical journal, Volume: 36, Issue: 6, (Nov. 1957): 1389-1401<br>
0 commit comments