Skip to content

prims algorithm greedy method.py #12079

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
48 changes: 48 additions & 0 deletions greedy_methods/prims algorithm greeedy method.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
def prims_algorithm(n, cost):

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

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

greedy_methods/prims algorithm greeedy method.py:1:1: N999 Invalid module name: 'prims algorithm greeedy method'
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 = u = b = v = -1 # Initialize variables

for i in range(1, n + 1):
for j in range(1, n + 1):
if cost[i][j] < min_cost:
if visited[i] == 0:
continue
else:
min_cost = cost[i][j]
a = u = i
b = v = j

if visited[u] == 0 or visited[v] == 0:
print(f"{ne}: edge({a}, {b}) = {min_cost}\t")
mincost += min_cost
visited[b] = 1
ne += 1

cost[a][b] = cost[b][a] = float('inf') # Mark the edge as processed

print(f"\nMinimum cost is {mincost}")


if __name__ == "__main__":
n = int(input("Enter the number of vertices in the graph: "))
cost = [[0] * (n + 1) for _ in range(n + 1)]

print("Enter the cost matrix of the graph:")
for i in range(1, n + 1):
for j in range(1, n + 1):
if i == j:
cost[i][j] = 0 # No self-loop
else:
cost[i][j] = int(input(f"({i},{j}): "))
if cost[i][j] == 0:
cost[i][j] = float('inf') # Use inf for no connection

prims_algorithm(n, cost)
Loading