Skip to content

Commit 90f531c

Browse files
committed
prims minimum spanning tree
1 parent 3f5f9e9 commit 90f531c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

graphs/prims.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# min spanning tree cost
2+
# prims
3+
import heapq
4+
5+
# min heap will contain a max of E total num of edges
6+
# time complexity E*log(E)
7+
# E = V^2 => log(E) = log(V^2) = 2*log(V)
8+
# time complexity: O(E*log(V))
9+
# space complexity: O(E)
10+
11+
def min_spanning_tree_cost(edges: list[int], n: int) -> int:
12+
adj = {i: [] for i in range(1, n + 1)}
13+
for u,v,w in edges:
14+
adj[u].append([w,v])
15+
minheap = [[0, 1]]
16+
visited = set()
17+
res = 0
18+
19+
20+
while minheap:
21+
w,u = heapq.heappop(minheap)
22+
if u in visited:
23+
continue
24+
visited.add(u)
25+
res += w
26+
for wei, nei in adj[u]:
27+
if not nei in visited:
28+
heapq.heappush(minheap, [wei, nei])
29+
return res
30+
edges = [[1,2,3],[1,3,5],[1,4,6],[2,3,1],[3,2,2],[3,4,1]]
31+
n = 4
32+
print(min_spanning_tree_cost(edges, n)) # 5

0 commit comments

Comments
 (0)