Ai 3 3166
Ai 3 3166
Roll no :- 3166
EXPERIMENT No :- 3
def prim_mst(graph):
"""
Prim's algorithm for Minimum Spanning Tree (MST) without heaps.
Args:
graph: A dictionary representing the graph. Keys are nodes, and values
are dictionaries of neighbor nodes with edge weights. Example:
graph = {
'A': {'B': 2, 'D': 6},
'B': {'A': 2, 'C': 3, 'D': 8, 'E': 5},
'C': {'B': 3, 'E': 7},
'D': {'A': 6, 'B': 8, 'E': 9, 'F': 11},
'E': {'B': 5, 'C': 7, 'D': 9, 'F': 15},
'F': {'D': 11, 'E': 15}
}
Returns:
A tuple containing:
- A list of tuples representing the edges of the MST.
- The total weight of the MST.
Returns None if the graph is empty.
""" if not
graph:
return None
nodes = list(graph.keys())
start_node = nodes[0] # Start from the first node
visited = {start_node} mst = [] total_weight =
0
if min_edge:
u, v, weight = min_edge
mst.append((u, v, weight))
total_weight += weight
visited.add(v) else:
# Handle disconnected graph case.
break
OUTPUT :-
C:\Users\bhumi\PycharmProjects\pythonProject9\venv\Scripts\python.exe
C:\Users\bhumi\PycharmProjects\pythonProject9\p3.py
A -- B : 2
B -- C : 3
B -- E : 5
A -- D : 6
D -- F : 11
A -- B : 1
A -- C : 2
B -- D : 5