IFI 8410 — Session 12: Graphs and Shortest Path
Questions about what lies between things
The problem
a network so a program can follow its connections quickly.
what can be reached from where, and which parts hang together.
the best route, once you say what is being measured.
The tools
dict, setrepresenting a graph
An adjacency list: each node mapped to its neighbours. "Is there an edge?" in one step.
collections.dequea queue
Add at one end, remove from the other, each in one step. The engine of breadth-first search.
heapqa priority queue
Always hands back the smallest item. The engine of shortest paths by distance.
the graph library
Graph objects, shortest paths with and without weights, components, hundreds of other algorithms.
The first three are enough to write every algorithm in this session by hand, which is worth doing once. For real work, networkx is tested, fast and complete.
Concept 1
| Called | Example | |
|---|---|---|
| the things | nodes (vertices) | people, airports, web pages, words |
| the connections between pairs of them | edges (links) | friendships, routes, hyperlinks |
Where a node is drawn means nothing. Only which nodes are joined matters. Neighbours are one edge away; degree is the number of edges at a node; a path is a sequence of nodes each joined to the next, its length counted in hops.
"Knows" goes both ways. "Follows", "links to" and "flies to" need not: whether a path exists then depends on the direction of travel.
An edge can carry a number: a distance, a travel time, a cost.
Concept 2
edges = [("Ana", "Ben"),
("Ana", "Chi"),
("Chi", "Dev")]Natural for a file. Poor to ask: "who are Dev's neighbours?" means reading every edge.
def build_graph(edges, directed=False):
graph = {}
for a, b in edges:
graph.setdefault(a, set())
graph.setdefault(b, set()) # b too!
graph[a].add(b)
if not directed:
graph[b].add(a)
return graphEvery node must be a key, with an empty collection if nothing leaves it. Otherwise: KeyError.
Concept 3
from collections import deque
def hop_distances(graph, start):
hops = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft() # FRONT
for neighbour in graph[node]:
if neighbour not in hops:
hops[neighbour] = hops[node] + 1
queue.append(neighbour) # BACK
return hopsConcept 3, continued
Taking from the back sends the search down one route as far as it goes. That is depth-first: the same nodes, with the wrong distances.
Otherwise any cycle traps the search for ever.
Not when it leaves, or it joins once for every edge that leads to it.
Concept 4
came_from = {start: None}
...
if neighbour not in came_from:
came_from[neighbour] = node
queue.append(neighbour)
path = []
node = target
while node is not None:
path.append(node)
node = came_from[node]
path.reverse()Shortest paths are not unique. Check that it is a real path of the right length, never that it is one particular path.
Concept 5
def components(graph):
seen, parts = set(), []
for node in graph:
if node not in seen:
part = set(hop_distances(graph, node)) # everything reachable
seen |= part
parts.append(part)
return partsLooking at the components is one of the first things to do with any real network.
Concept 6
Four towns. The direct road is 90 km. A route through two other towns uses three roads and totals 60 km. Breadth-first search returns the direct road: it counts roads.
| Breadth-first search | Dijkstra | |
|---|---|---|
| question | fewest edges | smallest total weight |
| takes next | the oldest node in the queue | the nearest node |
| container | deque | heapq |
| needs | nothing | weights that are not negative |
What "shortest" means is a modelling decision, made by what is put on the edges: 1 for fewest changes, kilometres, minutes, the fare.
The library
import networkx as nx
G = nx.Graph() # nx.DiGraph() for directed
G.add_weighted_edges_from(edges, weight="km")
nx.shortest_path(G, "Alba", "Dale") # fewest edges
nx.shortest_path(G, "Alba", "Dale", weight="km") # shortest distance
nx.connected_components(G)The same function gives two different routes depending on whether it is told about the weights. Forgetting weight= is the usual mistake, and it produces a plausible wrong answer.
Use case
About 37,000 routes between 3,300 airports. There is no direct flight from Atlanta to Sydney.
| Route | Flights | Distance | |
|---|---|---|---|
| fewest flights, as found | Atlanta → Dubai → Sydney | 2 | 24,000 km |
| fewest kilometres | Atlanta → Los Angeles → Sydney | 2 | 15,000 km |
Worked example — notebook 2
Each four-letter word is a node; two words that differ in one letter are joined: 2,400 nodes, 10,600 edges. The shortest ladder is a shortest path.
Most words are within five or six steps of COLD. The two farthest apart are seventeen steps from each other.
81 words have no neighbour at all. The second-largest component is a cluster of Roman numerals that had found their way into the word list.
Building it: comparing every pair of words grows with the square of their number. Filing each word under its four "one letter blanked" patterns in a dictionary does it in a hundredth of a second.
To take away
Now: hands-on
Folder 12-Graphs-Shortest-Path — work them in this order:
Concepts
Eight people and their friendships: building a graph, breadth-first search, paths, components, and weights. Four exercises.
Worked example
COLD to WARM in seven steps, checked against networkx. Run it on ARC.
Look things up
Graph patterns and networkx calls to keep open while you work.
As you work, ask of every network: what is a node, what is an edge, and what does "shortest" measure?
Homework: Homework 11: Fewest Hops

