Skip to content

Commit

Permalink
Fix steiner tree and Kruskal (#368)
Browse files Browse the repository at this point in the history
* fix kruskal and steiner tree

* fix eltype

* formatting

* Apply formatter

* update test

---------

Co-authored-by: Guillaume Dalle <[email protected]>
  • Loading branch information
etiennedeg and gdalle authored May 4, 2024
1 parent 0445886 commit 9c8efd9
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/spanningtrees/kruskal.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
kruskal_mst(g, distmx=weights(g); minimize=true)
kruskal_mst(g, distmx=weights(g); minimize=true)
Return a vector of edges representing the minimum (by default) spanning tree of a connected,
undirected graph `g` with optional distance matrix `distmx` using [Kruskal's algorithm](https://en.wikipedia.org/wiki/Kruskal%27s_algorithm).
Expand All @@ -15,6 +15,7 @@ function kruskal_mst end
connected_vs = IntDisjointSets(nv(g))

mst = Vector{edgetype(g)}()
nv(g) <= 1 && return mst
sizehint!(mst, nv(g) - 1)

weights = Vector{T}()
Expand Down
4 changes: 3 additions & 1 deletion src/steinertree/steiner_tree.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
filter_non_term_leaves!(g, term_vert)
filter_non_term_leaves!(g, term_vert)
Remove edges of `g` so that all non-isolated leaves of `g` are in the set `term_vert`
"""
Expand Down Expand Up @@ -44,6 +44,8 @@ function steiner_tree end
g::AG::(!IsDirected), term_vert::Vector{<:Integer}, distmx::AbstractMatrix{U}=weights(g)
) where {U<:Real,T,AG<:AbstractGraph{T}}
nvg = nv(g)
length(term_vert) == 0 && return SimpleGraph{T}()
length(term_vert) == 1 && return SimpleGraph{T}(first(term_vert))
term_to_actual = T.(term_vert)
unique!(term_to_actual)

Expand Down
9 changes: 9 additions & 0 deletions test/spanningtrees/kruskal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,13 @@
@test sort([(src(e), dst(e)) for e in mst2]) == sort([(src(e), dst(e)) for e in vec2])
@test sort([(src(e), dst(e)) for e in max_mst2]) == sort([(src(e), dst(e)) for e in max_vec2])
end

# non regression test for #362
g = Graph()
mst = @inferred(kruskal_mst(g))
@test isempty(mst)

g = Graph(1)
mst = @inferred(kruskal_mst(g))
@test isempty(mst)
end
4 changes: 4 additions & 0 deletions test/steinertree/steiner_tree.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
g_copy = SimpleGraph(g)
Graphs.filter_non_term_leaves!(g_copy, [2, 5])
@test ne(g_copy) == 2 # [Edge(2, 1), Edge(1, 5)]

# non regression test for #362
g_st = @inferred(steiner_tree(g, [2]))
@test ne(g_st) == 0
end

g4 = path_graph(11)
Expand Down

0 comments on commit 9c8efd9

Please sign in to comment.