liveBook · Manning

Weighted edge

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

A graph edge carrying a comparable value that represents a cost, distance, or other quantity associated with the connection.

A weighted edge connects two graph vertices while carrying a comparable value, such as distance or cost. Unlike an unweighted edge, it records both connectivity and information about the connection. section 4.1 section 4.3

The Swift implementation stores endpoint indices and a generic weight W. W must conform to Comparable so edges can be ordered, and to Summable so weights can be added. WeightedEdge compares edges by weight and can reverse itself for an undirected adjacency list. section 4.3 section 4.1

A practical weighted-edge design includes:

  • A weight property whose type may be Int, Double, Float, or another Comparable and Summable type. section 4.3
  • Endpoint indices u and v, plus a reversed edge carrying the same weight. section 4.3 section 4.1
  • A graph neighbor query that returns each neighboring vertex together with its edge weight. section 4.3

Distances in a city network

A graph of U.S. metropolitan areas assigns mile distances to connections, such as Seattle–San Francisco at 678 and Los Angeles–Riverside at 50. These values let Jarník's, or Prim's, algorithm select edges for a minimum spanning tree; the demonstrated network totals 5,372 miles. section 4.3

Figure 4.5. A weighted graph of the 15 largest MSAs in the United States, where each of the weights represents the distance between two MSAs in miles

A weighted graph figure makes the meaning of edge values concrete by displaying distances between metropolitan-area vertices. section 4.3

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

How deep it goes
Defines the structure and implements Swift generics, comparison, reversal, adjacency lookup, and weight addition; it stops short of formal proofs.
Examples
Demonstrates metropolitan-area distances, weighted neighbor output, and a 5,372-mile minimum spanning tree.
What it assumes
Assumes familiarity with vertices, edges, graphs, adjacency lists, and Swift protocols while distinguishing weighted from unweighted connections.
What you can do after
Build it from scratch as a generic Swift edge and use it in an undirected weighted graph.
How it connects
Connects weighted edges to graphs, adjacency lists, generic types, Comparable, Summable, and minimum spanning trees.

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.