Skip to content

Commit ac6a863

Browse files
Added Borůvka's algorithm, a graph algorithm that finds the minimum spanning tree. Solved Test Cases Errors.
1 parent c4a2e46 commit ac6a863

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

graphs/boruvka.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def set_component(self, u_node: int) -> None:
6262

6363
def union(self, component_size: list, u_node: int, v_node: int) -> None:
6464
"""Union finds the roots of components for two nodes, compares the components in terms of size,
65-
and attaches the smaller one to the larger one to form single component """
65+
and attaches the smaller one to the larger one to form single component """
6666

6767
if component_size[u_node] <= component_size[v_node]:
6868
self.m_component[u_node] = v_node
@@ -103,17 +103,23 @@ def boruvka(self) -> None:
103103
v_component = self.m_component[v]
104104

105105
if u_component != v_component:
106-
"""If the current minimum weight edge of component u doesn't exist (is -1), or if
107-
it's greater than the edge we're observing right now, we will assign the value
108-
of the edge we're observing to it.
109-
110-
If the current minimum weight edge of component v doesn't exist (is -1), or if
111-
it's greater than the edge we're observing right now, we will assign the value
112-
of the edge we're observing to it"""
113-
114-
if minimum_weight_edge[u_component] == -1 or minimum_weight_edge[u_component][2] > w:
106+
"""If the current minimum weight edge of component u doesn't exist (is -1), or if
107+
it's greater than the edge we're observing right now, we will assign the value
108+
of the edge we're observing to it.
109+
110+
If the current minimum weight edge of component v doesn't exist (is -1), or if
111+
it's greater than the edge we're observing right now, we will assign the value
112+
of the edge we're observing to it"""
113+
114+
if (
115+
minimum_weight_edge[u_component] == -1
116+
or minimum_weight_edge[u_component][2] > w
117+
):
115118
minimum_weight_edge[u_component] = [u, v, w]
116-
if minimum_weight_edge[v_component] == -1 or minimum_weight_edge[v_component][2] > w:
119+
if (
120+
minimum_weight_edge[v_component] == -1
121+
or minimum_weight_edge[v_component][2] > w
122+
):
117123
minimum_weight_edge[v_component] = [u, v, w]
118124

119125
for node in range(self.m_v):
@@ -128,9 +134,16 @@ def boruvka(self) -> None:
128134
if u_component != v_component:
129135
mst_weight += w
130136
self.union(component_size, u_component, v_component)
131-
print("Added edge [" + str(u) + " - "
132-
+ str(v) + "]\n"
133-
+ "Added weight: " + str(w) + "\n")
137+
print(
138+
"Added edge ["
139+
+ str(u)
140+
+ " - "
141+
+ str(v)
142+
+ "]\n"
143+
+ "Added weight: "
144+
+ str(w)
145+
+ "\n"
146+
)
134147
num_of_components -= 1
135148

136149
minimum_weight_edge = [-1] * self.m_v

0 commit comments

Comments
 (0)