|
| 1 | +from typing import Dict, Any |
| 2 | +import heapq |
| 3 | + |
| 4 | +def prim_mst(graph: Dict[Any, Dict[Any, int]]) -> Dict[Any, Any]: |
| 5 | + """ |
| 6 | + Generate the Minimum Spanning Tree (MST) using Prim's algorithm. |
| 7 | +
|
| 8 | + Args: |
| 9 | + graph (Dict[Any, Dict[Any, int]]): Adjacency dictionary of the graph where keys are nodes and |
| 10 | + values are dictionaries of neighbor nodes with edge weights. |
| 11 | +
|
| 12 | + Returns: |
| 13 | + Dict[Any, Any]: A dictionary representing the MST with each node pointing to its parent in the MST. |
| 14 | +
|
| 15 | + Example: |
| 16 | + >>> graph = { |
| 17 | + ... 'A': {'B': 2, 'C': 3}, |
| 18 | + ... 'B': {'A': 2, 'C': 1}, |
| 19 | + ... 'C': {'A': 3, 'B': 1} |
| 20 | + ... } |
| 21 | + >>> prim_mst(graph) |
| 22 | + {'A': 'B', 'B': 'C', 'C': 'B'} |
| 23 | + """ |
| 24 | + if not graph: |
| 25 | + return {} |
| 26 | + |
| 27 | + start_node = next(iter(graph)) |
| 28 | + visited = set([start_node]) |
| 29 | + edges = [(weight, start_node, to) for to, weight in graph[start_node].items()] |
| 30 | + heapq.heapify(edges) |
| 31 | + mst = {} |
| 32 | + |
| 33 | + while edges: |
| 34 | + weight, frm, to = heapq.heappop(edges) |
| 35 | + if to not in visited: |
| 36 | + visited.add(to) |
| 37 | + mst[to] = frm |
| 38 | + for next_to, next_weight in graph[to].items(): |
| 39 | + if next_to not in visited: |
| 40 | + heapq.heappush(edges, (next_weight, to, next_to)) |
| 41 | + |
| 42 | + return mst |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + import doctest |
| 46 | + doctest.testmod() |
0 commit comments