Skip to content

prims algorithm.py #12080

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions greedy_methods/prims algorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def prims_algorithm(n, cost):

Check failure on line 1 in greedy_methods/prims algorithm.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

greedy_methods/prims algorithm.py:1:1: N999 Invalid module name: 'prims algorithm'
visited = [0] * (n + 1) # Initialize visited array
visited[1] = 1 # Start from the first vertex
mincost = 0
ne = 1 # Number of edges in the spanning tree

print("The edges of the spanning tree are:")

while ne < n:
min_cost = float('inf')
a = b = -1 # Initialize edge endpoints

for i in range(1, n + 1):
if visited[i]: # Check only visited vertices
for j in range(1, n + 1):
if not visited[j] and cost[i][j] < min_cost:
min_cost = cost[i][j]
a, b = i, j

if a != -1 and b != -1: # Ensure valid edge found
print(f"{ne}: edge({a}, {b}) = {min_cost}\t")
mincost += min_cost
visited[b] = 1
ne += 1
Loading