Skip to content

Commit bab3b96

Browse files
authored
Update and rename Prim's_algorithm.cpp to Prim's_algorithm.py
1 parent 2f1710c commit bab3b96

File tree

2 files changed

+46
-64
lines changed

2 files changed

+46
-64
lines changed

greedy_methods/Prim's_algorithm.cpp

Lines changed: 0 additions & 64 deletions
This file was deleted.

greedy_methods/Prim's_algorithm.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from typing import Dict, Any
2+
import heapq
3+
4+
def prim_mst(graph: Dict[Any, Dict[Any, int]]) -> Dict[Any, Any]:
5+
"""
6+
Generate the Minimum Spanning Tree (MST) using Prim's algorithm.
7+
8+
Args:
9+
graph (Dict[Any, Dict[Any, int]]): Adjacency dictionary of the graph where keys are nodes and
10+
values are dictionaries of neighbor nodes with edge weights.
11+
12+
Returns:
13+
Dict[Any, Any]: A dictionary representing the MST with each node pointing to its parent in the MST.
14+
15+
Example:
16+
>>> graph = {
17+
... 'A': {'B': 2, 'C': 3},
18+
... 'B': {'A': 2, 'C': 1},
19+
... 'C': {'A': 3, 'B': 1}
20+
... }
21+
>>> prim_mst(graph)
22+
{'A': 'B', 'B': 'C', 'C': 'B'}
23+
"""
24+
if not graph:
25+
return {}
26+
27+
start_node = next(iter(graph))
28+
visited = set([start_node])
29+
edges = [(weight, start_node, to) for to, weight in graph[start_node].items()]
30+
heapq.heapify(edges)
31+
mst = {}
32+
33+
while edges:
34+
weight, frm, to = heapq.heappop(edges)
35+
if to not in visited:
36+
visited.add(to)
37+
mst[to] = frm
38+
for next_to, next_weight in graph[to].items():
39+
if next_to not in visited:
40+
heapq.heappush(edges, (next_weight, to, next_to))
41+
42+
return mst
43+
44+
if __name__ == "__main__":
45+
import doctest
46+
doctest.testmod()

0 commit comments

Comments
 (0)