Prim's Algorithm. Runtime: O(mn) with `m` edges and `n` vertices Return: List with the edges of a Minimum Spanning Tree Usage: prim(graph, graph[0])
(graph: list, root: Vertex)
| 54 | |
| 55 | |
| 56 | def prim(graph: list, root: Vertex) -> list: |
| 57 | """Prim's Algorithm. |
| 58 | |
| 59 | Runtime: |
| 60 | O(mn) with `m` edges and `n` vertices |
| 61 | |
| 62 | Return: |
| 63 | List with the edges of a Minimum Spanning Tree |
| 64 | |
| 65 | Usage: |
| 66 | prim(graph, graph[0]) |
| 67 | """ |
| 68 | a = [] |
| 69 | for u in graph: |
| 70 | u.key = math.inf |
| 71 | u.pi = None |
| 72 | root.key = 0 |
| 73 | q = graph[:] |
| 74 | while q: |
| 75 | u = min(q) |
| 76 | q.remove(u) |
| 77 | for v in u.neighbors: |
| 78 | if (v in q) and (u.edges[v.id] < v.key): |
| 79 | v.pi = u |
| 80 | v.key = u.edges[v.id] |
| 81 | for i in range(1, len(graph)): |
| 82 | a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) |
| 83 | return a |
| 84 | |
| 85 | |
| 86 | def prim_heap(graph: list, root: Vertex) -> Iterator[tuple]: |