WeightedGraph

open class WeightedGraph<V, W> : Graph where V : Decodable, V : Encodable, V : Equatable, W : Decodable, W : Encodable, W : Equatable

An implementation of Graph that has convenience methods for adding and removing WeightedEdges. All added Edges should have the same generic Comparable type W as the WeightedGraph itself.

Available where W: Comparable

  • Find the minimum spanning tree in a weighted graph. This is the set of edges that touches every vertex in the graph and is of minimal combined weight. This function uses Jarnik’s Algorithm (aka Prim’s Algorithm) and so assumes the graph has undirected edges. For a graph with directed edges, the result may be incorrect. Also, if the graph is not fully connected, the tree will only span the connected component from which the starting vertex belongs.

    Declaration

    Swift

    func mst(start: Int = 0) -> [WeightedEdge<W>]?

    Parameters

    start

    The index of the vertex to start creating the MST from.

    Return Value

    An array of WeightedEdges containing the minimum spanning tree, or nil if the starting vertex is invalid. If there are is only one vertex connected to the starting vertex, an empty list is returned.

Available where W: Comparable & Numeric

  • Finds the shortest paths from some route vertex to every other vertex in the graph.

    Declaration

    Swift

    func dijkstra(root: Int, startDistance: W) -> ([W?], [Int : WeightedEdge<W>])

    Parameters

    graph

    The WeightedGraph to look within.

    root

    The index of the root node to build the shortest paths from.

    startDistance

    The distance to get to the root node (typically 0).

    Return Value

    Returns a tuple of two things: the first, an array containing the distances, the second, a dictionary containing the edge to reach each vertex. Use the function pathDictToPath() to convert the dictionary into something useful for a specific point.

  • A convenience version of dijkstra() that allows the supply of the root vertex instead of the index of the root vertex.

    Declaration

    Swift

    func dijkstra(root: V, startDistance: W) -> ([W?], [Int : WeightedEdge<W>])