@@ -4,6 +4,8 @@ import ..Network: Connection, nodes
44
55import .. OperationsResearchModels: solve
66
7+ import LinearAlgebra: issymmetric
8+
79export hasloop
810export MstResult
911export MstProblem
@@ -17,15 +19,16 @@ export MstProblem
1719Defines the minimum spanning tree problem.
1820
1921# Fields
20- - `connections::Vector{Connection}`: The connections (edges) in the network.
22+ - `data::Union{Vector{Connection}, AbstractMatrix{<:Real}}`: The data representing the network.
23+ It can be either a vector of connections or a distance matrix.
2124
2225!!! info "Interpreting the Connection object"
2326
2427 The Connection object defines a directed edge, but for the minimum spanning tree problem,
2528 the edges are considered undirected.
2629"""
2730struct MstProblem
28- connections :: Vector{Connection}
31+ data :: Union{ Vector{Connection}, AbstractMatrix{<:Real} }
2932end
3033
3134
@@ -120,6 +123,27 @@ function makedistancematrix(conns::Vector{Connection})::Matrix
120123end
121124
122125
126+
127+ function makeconnections (mat:: Matrix ):: Vector{Connection}
128+
129+ n, _ = size (mat)
130+
131+ ! issymmetric (mat) && throw (AssertionError (" The distance matrix must be symmetric." ))
132+
133+ conns = Vector {Connection} (undef, n * (n- 1 ) ÷ 2 )
134+ idx = 1
135+ for i = 1 : n
136+ for j = (i+ 1 ): n
137+ conns[idx] = Connection (i, j, mat[i, j])
138+ idx += 1
139+ end
140+ end
141+
142+ return conns
143+
144+ end
145+
146+
123147"""
124148 solve(problem::MstProblem)
125149
@@ -160,11 +184,19 @@ println(result.connections)
160184"""
161185function solve (problem:: MstProblem ):: MstResult
162186
163- conns = problem. connections
187+ if problem. data isa AbstractMatrix
188+ conns = makeconnections (problem. data)
189+ distmat = problem. data
190+ else
191+ conns = problem. data
192+ distmat = makedistancematrix (conns)
193+ end
194+
195+ # conns = problem.connections
164196
165- totaldist = 0.0
197+ # distmat = makedistancematrix(conns)
166198
167- distmat = makedistancematrix (conns)
199+ totaldist = 0.0
168200
169201 assigned = Set {Int64} ()
170202 unassigned = nodes (conns)
0 commit comments