fork download
  1. import sys
  2.  
  3. def prims_algorithm(graph):
  4. num_vertices = len(graph)
  5. selected = [False] * num_vertices
  6. selected[0] = True # Start from the first vertex
  7.  
  8. edges = []
  9. total_weight = 0
  10.  
  11. for _ in range(num_vertices - 1):
  12. min_edge = (sys.maxsize, None, None) # (weight, start_vertex, end_vertex)
  13.  
  14. for start in range(num_vertices):
  15. if selected[start]:
  16. for end in range(num_vertices):
  17. if not selected[end] and graph[start][end]:
  18. if graph[start][end] < min_edge[0]:
  19. min_edge = (graph[start][end], start, end)
  20.  
  21. weight, start_vertex, end_vertex = min_edge
  22. edges.append((start_vertex, end_vertex, weight))
  23. total_weight += weight
  24. selected[end_vertex] = True
  25.  
  26. return total_weight, edges
  27.  
  28. # Example usage
  29. graph = [
  30. [0, 4, 3, 0],
  31. [4, 0, 1, 2],
  32. [3, 1, 0, 4],
  33. [0, 2, 4, 0]
  34. ]
  35.  
  36. total_weight, mst_edges = prims_algorithm(graph)
  37. print(f"Total weight of MST: {total_weight}")
  38. print("Edges in the MST:")
  39. for edge in mst_edges:
  40. print(f"{edge[0]} -- {edge[1]} with weight {edge[2]}")
  41.  
  42.  
Success #stdin #stdout 0.03s 25952KB
stdin
Standard input is empty
stdout
import sys

def prims_algorithm(graph):
    num_vertices = len(graph)
    selected = [False] * num_vertices
    selected[0] = True  # Start from the first vertex

    edges = []
    total_weight = 0

    for _ in range(num_vertices - 1):
        min_edge = (sys.maxsize, None, None)  # (weight, start_vertex, end_vertex)

        for start in range(num_vertices):
            if selected[start]:
                for end in range(num_vertices):
                    if not selected[end] and graph[start][end]:
                        if graph[start][end] < min_edge[0]:
                            min_edge = (graph[start][end], start, end)

        weight, start_vertex, end_vertex = min_edge
        edges.append((start_vertex, end_vertex, weight))
        total_weight += weight
        selected[end_vertex] = True

    return total_weight, edges

# Example usage
graph = [
    [0, 4, 3, 0],
    [4, 0, 1, 2],
    [3, 1, 0, 4],
    [0, 2, 4, 0]
]

total_weight, mst_edges = prims_algorithm(graph)
print(f"Total weight of MST: {total_weight}")
print("Edges in the MST:")
for edge in mst_edges:
    print(f"{edge[0]} -- {edge[1]} with weight {edge[2]}")