graphs.boruvka¶
Borůvka’s algorithm.
Determines the minimum spanning tree (MST) of a graph using the Borůvka’s algorithm. Borůvka’s algorithm is a greedy algorithm for finding a minimum spanning tree in a connected graph, or a minimum spanning forest if a graph that is not connected.
The time complexity of this algorithm is O(ELogV), where E represents the number of edges, while V represents the number of nodes. O(number_of_edges Log number_of_nodes)
The space complexity of this algorithm is O(V + E), since we have to keep a couple of lists whose sizes are equal to the number of nodes, as well as keep all the edges of a graph inside of the data structure itself.
Borůvka’s algorithm gives us pretty much the same result as other MST Algorithms - they all find the minimum spanning tree, and the time complexity is approximately the same.
One advantage that Borůvka’s algorithm has compared to the alternatives is that it doesn’t need to presort the edges or maintain a priority queue in order to find the minimum spanning tree. Even though that doesn’t help its complexity, since it still passes the edges logE times, it is a bit simpler to code.
Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm
Classes¶
Functions¶
|
Module Contents¶
- class graphs.boruvka.Graph(num_of_nodes: int)¶
- add_edge(u_node: int, v_node: int, weight: int) None ¶
Adds an edge in the format [first, second, edge weight] to graph.
- boruvka() None ¶
Performs Borůvka’s algorithm to find MST.
- find_component(u_node: int) int ¶
Propagates a new component throughout a given component.
- set_component(u_node: int) None ¶
Finds the component index of a given node
- union(component_size: list[int], u_node: int, v_node: int) None ¶
Union finds the roots of components for two nodes, compares the components in terms of size, and attaches the smaller one to the larger one to form single component
- m_component: dict[int, int]¶
- m_edges: list[list[int]] = []¶
- m_num_of_nodes¶
- graphs.boruvka.test_vector() None ¶
>>> g = Graph(8) >>> for u_v_w in ((0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4), ... (3, 4, 8), (4, 5, 10), (4, 6, 6), (4, 7, 5), (5, 7, 15), (6, 7, 4)): ... g.add_edge(*u_v_w) >>> g.boruvka() Added edge [0 - 3] Added weight: 5 Added edge [0 - 1] Added weight: 10 Added edge [2 - 3] Added weight: 4 Added edge [4 - 7] Added weight: 5 Added edge [4 - 5] Added weight: 10 Added edge [6 - 7] Added weight: 4 Added edge [3 - 4] Added weight: 8 The total weight of the minimal spanning tree is: 46