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

Function prims_algo

graphs/minimum_spanning_tree_prims2.py:220–269  ·  view source on GitHub ↗

>>> graph = GraphUndirectedWeighted() >>> graph.add_edge("a", "b", 3) >>> graph.add_edge("b", "c", 10) >>> graph.add_edge("c", "d", 5) >>> graph.add_edge("a", "c", 15) >>> graph.add_edge("b", "d", 100) >>> dist, parent = prims_algo(graph) >>> abs(dist["a"] - dist[

(
    graph: GraphUndirectedWeighted[T],
)

Source from the content-addressed store, hash-verified

218
219
220def prims_algo[T](
221 graph: GraphUndirectedWeighted[T],
222) -> tuple[dict[T, int], dict[T, T | None]]:
223 """
224 >>> graph = GraphUndirectedWeighted()
225
226 >>> graph.add_edge("a", "b", 3)
227 >>> graph.add_edge("b", "c", 10)
228 >>> graph.add_edge("c", "d", 5)
229 >>> graph.add_edge("a", "c", 15)
230 >>> graph.add_edge("b", "d", 100)
231
232 >>> dist, parent = prims_algo(graph)
233
234 >>> abs(dist["a"] - dist["b"])
235 3
236 >>> abs(dist["d"] - dist["b"])
237 15
238 >>> abs(dist["a"] - dist["c"])
239 13
240 """
241 # prim's algorithm for minimum spanning tree
242 dist: dict[T, int] = dict.fromkeys(graph.connections, maxsize)
243 parent: dict[T, T | None] = dict.fromkeys(graph.connections)
244
245 priority_queue: MinPriorityQueue[T] = MinPriorityQueue()
246 for node, weight in dist.items():
247 priority_queue.push(node, weight)
248
249 if priority_queue.is_empty():
250 return dist, parent
251
252 # initialization
253 node = priority_queue.extract_min()
254 dist[node] = 0
255 for neighbour in graph.connections[node]:
256 if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
257 dist[neighbour] = dist[node] + graph.connections[node][neighbour]
258 priority_queue.update_key(neighbour, dist[neighbour])
259 parent[neighbour] = node
260
261 # running prim's algorithm
262 while not priority_queue.is_empty():
263 node = priority_queue.extract_min()
264 for neighbour in graph.connections[node]:
265 if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
266 dist[neighbour] = dist[node] + graph.connections[node][neighbour]
267 priority_queue.update_key(neighbour, dist[neighbour])
268 parent[neighbour] = node
269 return dist, parent

Callers

nothing calls this directly

Calls 5

pushMethod · 0.95
is_emptyMethod · 0.95
extract_minMethod · 0.95
update_keyMethod · 0.95
MinPriorityQueueClass · 0.85

Tested by

no test coverage detected