Skip to content

Commit 977786a

Browse files
committed
myst
1 parent db337c4 commit 977786a

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed

content/algorithms/MST Prim/MST Prim.md

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,37 @@
11
---
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
1312
---
1413

1514
# Minimum Spanning Tree using Prim's Algorithm
1615

16+
+++
1717

1818
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.
1919

2020
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.
2121

22+
+++
2223

2324
## Minimum Spanning Tree Problem
2425

26+
+++
2527

2628
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.
2729

2830
<b>ASSUMPTION</b>: Distance taken is imaginary.
2931

3032
The following graph depicts our situation in this case.
3133

32-
```python
34+
```{code-cell} ipython3
3335
# importing libraries
3436
import networkx as nx
3537
import matplotlib.pyplot as plt
@@ -76,12 +78,12 @@ nx.draw_networkx_edge_labels(
7678
edge_labels=nx.get_edge_attributes(roads, "weight"),
7779
font_size=12,
7880
);
79-
8081
```
8182

8283
Now, in order to find the minimum spanning tree, this notepad will cover the Prim's algorithm.
8384
Let's understand it in detail.
8485

86+
+++
8587

8688
## Prim's Algorithm
8789
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
9597
4. Repeat steps 2 and 3 until all nodes are covered.
9698
5. The final graph will represent the Minimum Spanning Tree
9799

100+
+++
98101

99102
### Example solution
100103
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:
101104
- Red nodes represent unvisited vertices while green nodes represent visited vertices.
102105
- Edges of minimum spanning tree are represented in purple color.
103106

104-
```python
107+
```{code-cell} ipython3
105108
# converting graph to dictionary
106109
road_list = roads._adj
107110
@@ -115,7 +118,7 @@ inf = 1 + max([w['weight'] for u in road_list.keys() for (v,w) in road_list[u].i
115118
### Step 1
116119
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).
117120

118-
```python
121+
```{code-cell} ipython3
119122
# assigning infinite distance to all nodes and marking all nodes as not visited
120123
for v in road_list.keys():
121124
(visited[v], distance[v]) = (False, inf) # false indicates not visited
@@ -169,7 +172,7 @@ Here, the following nodes will get updated:
169172
- B : `min(1, 8) = 1`
170173
- C : `min(7, 8) = 7`
171174

172-
```python
175+
```{code-cell} ipython3
173176
# updating weights of A's neighbour
174177
for (v, w) in road_list["A"].items():
175178
distance[v] = w["weight"]
@@ -202,13 +205,12 @@ nx.draw_networkx_edge_labels(
202205
edge_labels=nx.get_edge_attributes(roads, "weight"),
203206
font_size=12,
204207
);
205-
206208
```
207209

208210
### Step 3 & Step 4
209211
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.
210212

211-
```python
213+
```{code-cell} ipython3
212214
# initialising the required dictionaries for plotting graphs
213215
visited_list = []
214216
distance_list = []
@@ -238,7 +240,6 @@ for i in road_list.keys():
238240
if not visited[v]:
239241
distance[v] = min(distance[v], d)
240242
distance_list.append(distance.copy())
241-
242243
```
243244

244245
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
265266
<b>Figure 4</b><br>
266267
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.
267268

268-
```python
269+
```{code-cell} ipython3
269270
fig, axes = plt.subplots(2, 2, figsize=(15,15))
270271
c=0
271272
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):
315316
### Step 5
316317
The final output of the program is stored as a list of tuples in `TreeEdges` as shown below.
317318

318-
```python
319+
```{code-cell} ipython3
319320
print(TreeEdges)
320321
```
321322

@@ -325,7 +326,7 @@ The above code is a basic implementation of Prim's algorithm with the time compl
325326
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>
326327
The following code uses NetworkX function and gives us the same output as our code.
327328

328-
```python
329+
```{code-cell} ipython3
329330
MST= nx.minimum_spanning_tree(roads, algorithm= "prim")
330331
print(sorted(MST.edges(data=True)))
331332
```
@@ -340,6 +341,7 @@ print(sorted(MST.edges(data=True)))
340341

341342
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.
342343

344+
+++
343345

344346
## Reference
345347
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

Comments
 (0)