Skip to content

Commit 1f1f61f

Browse files
authored
prims algorithm.py
1 parent 03a4251 commit 1f1f61f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

greedy_methods/prims algorithm.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
def prims_algorithm(n, cost):
2+
visited = [0] * (n + 1) # Initialize visited array
3+
visited[1] = 1 # Start from the first vertex
4+
mincost = 0
5+
ne = 1 # Number of edges in the spanning tree
6+
7+
print("The edges of the spanning tree are:")
8+
9+
while ne < n:
10+
min_cost = float('inf')
11+
a = b = -1 # Initialize edge endpoints
12+
13+
for i in range(1, n + 1):
14+
if visited[i]: # Check only visited vertices
15+
for j in range(1, n + 1):
16+
if not visited[j] and cost[i][j] < min_cost:
17+
min_cost = cost[i][j]
18+
a, b = i, j
19+
20+
if a != -1 and b != -1: # Ensure valid edge found
21+
print(f"{ne}: edge({a}, {b}) = {min_cost}\t")
22+
mincost += min_cost
23+
visited[b] = 1
24+
ne += 1

0 commit comments

Comments
 (0)