Skip to content

Commit 038d30a

Browse files
authored
Add Prim's algorithm implementation (using Priority Queue)
Implement Prim's algorithm to find the minimum spanning tree of a graph using a priority queue.
1 parent 788d95b commit 038d30a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import heapq
2+
3+
def prim_mst(graph, start=0):
4+
visited = set()
5+
mst = []
6+
total_cost = 0
7+
8+
# Min-heap (cost, current_node, next_node)
9+
edges = [(0, start, start)]
10+
11+
while edges:
12+
cost, u, v = heapq.heappop(edges)
13+
if v in visited:
14+
continue
15+
visited.add(v)
16+
total_cost += cost
17+
if u != v:
18+
mst.append((u, v, cost))
19+
for neighbor, weight in graph[v]:
20+
if neighbor not in visited:
21+
heapq.heappush(edges, (weight, v, neighbor))
22+
23+
return mst, total_cost
24+
25+
26+
# Example Graph as adjacency list
27+
graph = {
28+
0: [(1, 2), (3, 6)],
29+
1: [(0, 2), (2, 3), (3, 8), (4, 5)],
30+
2: [(1, 3), (4, 7)],
31+
3: [(0, 6), (1, 8)],
32+
4: [(1, 5), (2, 7)]
33+
}
34+
35+
mst, cost = prim_mst(graph)
36+
print("Edges in MST:", mst)
37+
print("Total Cost:", cost)

0 commit comments

Comments
 (0)