We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 03a4251 commit 1f1f61fCopy full SHA for 1f1f61f
greedy_methods/prims algorithm.py
@@ -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