Skip to content

Commit

Permalink
Cleanup graph code, fix code duplication.
Browse files Browse the repository at this point in the history
  • Loading branch information
renggli committed Apr 28, 2024
1 parent 1e1b6a7 commit cd22ead
Show file tree
Hide file tree
Showing 3 changed files with 1 addition and 10 deletions.
4 changes: 0 additions & 4 deletions lib/src/graph/algorithms/kruskal_spanning_tree.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,17 @@ Graph<V, E> kruskalSpanningTree<V, E>(
// Create an empty copy of the graph.
final result = graph.copy(empty: true);
result.addVertices(graph.vertices);

// Fetch and sort the edges, if any.
final edges = graph.edges.toList(growable: false);
if (edges.isEmpty) return result;
edges.sortByCompare(
(value) => edgeWeight(value.source, value.target),
weightComparator,
);

// State for each vertex.
final states = vertexStrategy.createMap<_State<V>>();
_State<V> getState(V vertex) =>
states.putIfAbsent(vertex, () => _State(vertex));

// Process all the edges.
for (final edge in edges) {
final source = getState(edge.source);
Expand All @@ -46,7 +43,6 @@ Graph<V, E> kruskalSpanningTree<V, E>(
result.addEdge(edge.source, edge.target, value: edge.value);
}
}

return result;
}

Expand Down
3 changes: 0 additions & 3 deletions lib/src/graph/algorithms/prim_spanning_tree.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ Graph<V, E> primSpanningTree<V, E>(
}) {
// Create an empty copy of the graph.
final result = graph.copy(empty: true);

// Queue for the shortest remaining edges.
final queue = PriorityQueue<_State<V, E>>(
weightComparator.onResultOf((state) => state.cost));
Expand All @@ -33,7 +32,6 @@ Graph<V, E> primSpanningTree<V, E>(

// Prepare the initial outgoing edges.
addOutgoingEdgesToQueue(startVertex ?? graph.vertices.first);

// Pick the shortest edge that connects to a not yet connected vertex.
while (queue.isNotEmpty) {
final state = queue.removeFirst();
Expand All @@ -43,7 +41,6 @@ Graph<V, E> primSpanningTree<V, E>(
addOutgoingEdgesToQueue(state.edge.target);
}
}

return result;
}

Expand Down
4 changes: 1 addition & 3 deletions lib/src/graph/operations/logical.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ extension LogicalGraphExtension<V, E> on Graph<V, E> {
{E Function(V source, V target, E a, E b)? edgeMerge}) {
for (final graph in others) {
// Create all vertices present in any graph.
for (final vertex in graph.vertices) {
result.addVertex(vertex);
}
result.addVertices(graph.vertices);
// Create all edges present in any graph.
for (final vertex in graph.vertices) {
for (final edge in graph.outgoingEdgesOf(vertex)) {
Expand Down

0 comments on commit cd22ead

Please sign in to comment.