liveBook · Manning

Weighted graph

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A weighted graph is a graph whose edges have associated values representing connection costs or other quantities.

Suppose each proposed rail link between two cities has a distance in miles. An unweighted graph says which cities connect; a weighted graph also records the distance of each connection. Those values make it possible to ask which links minimize a network’s total length or which route is shortest from a starting city. section 4.1 section 4.3 section 4.4

In Swift, `WeightedEdge<W>` stores endpoint indices `u` and `v` plus a `weight`. `WeightedGraph<V, W>` keeps vertices and adjacency lists of those edges. Its weighted-neighbor method returns `(vertex, weight)` pairs. The graph’s edge insertion is bidirectional: it also stores a reversed edge, preserving the weight. section 4.3 section 4.1

open class WeightedEdge<W: Comparable & Summable>: Edge, Comparable {
    public var u: Int
    public var v: Int
    public let weight: W

    public var reversed: Edge {
        return WeightedEdge(u: v, v: u, weight: weight)
    }

    public init(u: Int, v: Int, weight: W) {
        self.weight = weight
        self.u = u
        self.v = v
    }

    //Implement CustomStringConvertible protocol
    public var description: String {
        return "\(u) <\(weight)> \(v)"
    }

    //MARK: Operator Overloads for Comparable
    static public func == <W>(lhs: WeightedEdge<W>,
     rhs: WeightedEdge<W>) -> Bool {
        return lhs.u == rhs.u && lhs.v == rhs.v && lhs.weight == rhs.weight
    }

    static public func < <W>(lhs: WeightedEdge<W>, rhs:
     WeightedEdge<W>) -> Bool {
        return lhs.weight < rhs.weight
    }
}

Inspect how the edge retains its weight when reversed and compares edges by weight for selecting low-cost links. section 4.3

Weights are generic, but the algorithms need to compare and add them. `Comparable` supplies comparisons; the custom `Summable` protocol requires `+`. The implementation adds `Summable` conformance to `Int`, `Double`, and `Float`. An empty collection of weighted edges has no first weight to start a total, so `totalWeight` returns an optional result. section 4.3

A city network

A `WeightedGraph<String, Int>` can contain Seattle, San Francisco, and their other proposed connections. Adding Seattle–San Francisco with weight `678` records a 678-mile link; a weighted-neighbor listing shows San Francisco alongside `678`. The same larger network supports a minimum spanning tree with total weight `5372` and a shortest route from Los Angeles to Boston with total weight `2605`. section 4.3 section 4.4

Two questions use the weights differently:

  • A minimum spanning tree selects low-weight edges that connect the vertices without cycles. The priority-queue implementation assumes undirected edges; if the graph is disconnected, it spans only the starting vertex’s component. section 4.3
  • A single-source shortest-path search finds the lowest total edge weight from one vertex to each other vertex. Dijkstra’s algorithm records distances and the edge used to reach each vertex, updating them when it finds a shorter route. section 4.4

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Builds generic weighted edges and adjacency lists, then walks through priority-queue implementations of spanning-tree and shortest-path searches.
Examples
Uses mile-weighted links among 15 U.S. metropolitan areas, a 5372-mile spanning tree, and a 2605-mile Los Angeles–Boston route.
What it assumes
Assumes familiarity with Swift syntax while developing weighted edges from an existing unweighted graph framework and defining addition support.
What you can do after
Build it from scratch as a generic Swift graph and apply it to minimum spanning trees and single-source shortest paths.
How it connects
Connects adjacency lists, generic protocols, minimum spanning trees, priority queues, and Dijkstra’s algorithm.

Also explained in

Compare how 3 books explain weighted graph →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.