MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / prim

Function prim

graphs/prim.py:56–83  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

54
55
56def 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
86def prim_heap(graph: list, root: Vertex) -> Iterator[tuple]:

Callers

nothing calls this directly

Calls 2

removeMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected