---
title: "Graph Traversals and Shortest Paths"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 26
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 26 — Graph Traversals and Shortest Paths

A classic way out of a maze is to put one hand on a wall and never let go. It works in every maze whose exit is on the outer wall, and it needs no memory at all. But it walks into every dead end on its side, and comes back out of each: the way it finds is rarely the shortest.

This chapter writes the two systematic ways of exploring a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), depth first with a stack and breadth first with a queue, and uses them to decide what can be reached, to find [cycles](#def-g12-graph-algorithms-cycle) and to find shortest paths counted in edges. Then the edges get lengths, and [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) finds the shortest routes across the town.

**You already know.**

A [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) is made of vertices and edges, possibly directed and weighted; a path, its length, the distance between two vertices, and the components of a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) were defined in chapter [9](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#ch-g10-graphs-first-look), where the town’s road [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) was first loaded. A stack gives back its newest element first, a queue its oldest (chapter [24](https://one-course.com/books/computer-science/2/en/chapter/24-linked-lists-stacks-and-queues#ch-g12-lists-stacks-queues)). The adjacency matrix of a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) (the mathematics book).

## 26.1 Representations

**Definition 26.1 (Adjacency list, successor, predecessor).**

The *adjacency lists* of a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) give, for each vertex, the list of its neighbours; in Python, a dictionary from each vertex to that list. In a [directed graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed), the vertices at the end of the edges leaving $v$ are its *successors*, and those at the start of the edges arriving at $v$ its *predecessors*; the lists usually give the successors.

The adjacency matrix of a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) of $n$ vertices is an $n \times n$ table of $0$ and $1$, with a $1$ in row $v$ and column $w$ when there is an edge from $v$ to $w$.

```python
"""One graph, two representations: adjacency lists and adjacency matrix."""
G = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],
     "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"]}


def to_matrix(adj):
    names = sorted(adj)
    index = {v: i for i, v in enumerate(names)}
    m = [[0] * len(names) for _ in names]
    for v in adj:
        for w in adj[v]:
            m[index[v]][index[w]] = 1
    return names, m


def to_lists(names, m):
    return {v: [names[j] for j, x in enumerate(row) if x] for v, row in zip(names, m)}


if __name__ == "__main__":
    names, m = to_matrix(G)
    for v, row in zip(names, m):
        print(v, row, "| neighbours:", G[v])
    print("back to lists, same graph:", to_lists(names, m) == G)

    # a directed graph: successors are given, predecessors are computed
    succ = {"wake": ["dress", "eat"], "dress": ["leave"], "eat": ["leave"], "leave": []}
    pred = {v: [u for u in succ if v in succ[u]] for v in succ}
    print("predecessors:", pred)
```

***Listing 26.1.** The two representations, converted both ways, and the [predecessors](#def-g12-graph-algorithms-adjacency-list) of a [directed graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed). code/grade-12/05-graph-algorithms/listings/representations.py*

```
$ python representations.py
A [0, 1, 1, 0, 0, 0] | neighbours: ['B', 'C']
B [1, 0, 0, 1, 0, 0] | neighbours: ['A', 'D']
C [1, 0, 0, 1, 1, 0] | neighbours: ['A', 'D', 'E']
D [0, 1, 1, 0, 0, 1] | neighbours: ['B', 'C', 'F']
E [0, 0, 1, 0, 0, 1] | neighbours: ['C', 'F']
F [0, 0, 0, 1, 1, 0] | neighbours: ['D', 'E']
back to lists, same graph: True
predecessors: {'wake': [], 'dress': ['wake'], 'eat': ['wake'], 'leave': ['dress', 'eat']}
```

***Output 26.1.** Each row of the matrix holds the same information as one list.*

![The graph G of the listings, its adjacency lists and its adjacency matrix (rows and columns in the order A to F). The matrix is symmetric because the graph is undirected.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-graph-algorithms/fig-a454443417be.svg)

*The [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) `G` of the listings, its [adjacency lists](#def-g12-graph-algorithms-adjacency-list) and its adjacency matrix (rows and columns in the order A to F). The matrix is symmetric because the [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) is undirected.*

The two cost differently. The matrix always takes $n^2$ cells, and answers “is there an edge from $v$ to $w$?” in one step. The lists take one entry per edge end, and list the neighbours of $v$ without looking at the others. For a town of $30$ places and $53$ roads the lists are far smaller; most [graphs](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) met in practice are like it, with few edges per vertex, and are stored as lists.

## 26.2 Depth-first search

**Method 26.2 (Depth-first search).**

A *depth-first search* explores a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) from a starting vertex by always going on from the most recently found vertex: visit it, mark it as visited, then search from each of its unvisited neighbours in turn, before coming back. A stack holds the vertices still to explore; the recursion’s [call stack](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#def-g12-recursion-call-stack) can play that role.

```python
from representations import G


def dfs_stack(g, start):
    """Depth-first order with an explicit stack."""
    order, visited, stack = [], set(), [start]
    while stack:
        v = stack.pop()
        if v in visited:
            continue
        visited.add(v)
        order.append(v)
        for w in reversed(g[v]):            # reversed: the first neighbour on top
            if w not in visited:
                stack.append(w)
    return order


def dfs_rec(g, v, visited=None):
    """The same order, with the call stack of the recursion."""
    if visited is None:
        visited = []
    visited.append(v)
    for w in g[v]:
        if w not in visited:
            dfs_rec(g, w, visited)
    return visited


if __name__ == "__main__":
    print("with a stack:   ", dfs_stack(G, "A"))
    print("with recursion: ", dfs_rec(G, "A"))
    print("reachable from E:", sorted(dfs_stack(G, "E")))
```

***Listing 26.2.** Depth-first search with a stack and with recursion. code/grade-12/05-graph-algorithms/listings/dfs.py*

```
$ python dfs.py
with a stack:    ['A', 'B', 'D', 'C', 'E', 'F']
with recursion:  ['A', 'B', 'D', 'C', 'E', 'F']
reachable from E: ['A', 'B', 'C', 'D', 'E', 'F']
```

***Output 26.2.** Both versions give the same order; everything is reachable from E.*

![The depth-first search of G from A: the numbers give the order of visit. Bold edges are those used to reach a new vertex; they form a tree. The dashed edges lead to vertices already visited.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-graph-algorithms/fig-503c9cfc983d.svg)

*The depth-first search of `G` from A: the numbers give the order of visit. Bold edges are those used to reach a new vertex; they form a tree. The dashed edges lead to vertices already visited.*

A search from $v$ visits exactly the vertices reachable from $v$; each vertex is visited once, and each edge looked at once from each end, so the cost is proportional to the number of vertices plus the number of edges.

**Definition 26.3 (Cycle).**

A *cycle* is a path of at least one edge that comes back to its first vertex without using any edge twice; in an undirected [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), it has at least three vertices.

In an undirected [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), a depth-first search that meets an already visited vertex, other than the one it came from, has found a [cycle](#def-g12-graph-algorithms-cycle). In a [directed graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed) that is not enough: two paths may join without any [cycle](#def-g12-graph-algorithms-cycle). The search then gives each vertex one of three colours: white, not yet seen; grey, being explored, its search not finished; black, finished. An edge to a grey vertex goes back to a vertex whose search is still running, so there is a path from it to the present vertex and back: a [cycle](#def-g12-graph-algorithms-cycle).

```python
def has_cycle_undirected(g):
    """A cycle exists if the search meets a visited vertex other than its parent."""
    visited = set()
    for root in g:
        if root in visited:
            continue
        visited.add(root)
        stack = [(root, None)]
        while stack:
            v, parent = stack.pop()
            for w in g[v]:
                if w not in visited:
                    visited.add(w)
                    stack.append((w, v))
                elif w != parent:
                    return True
    return False


WHITE, GREY, BLACK = 0, 1, 2      # not seen, being explored, finished


```

***Listing 26.3.** [Cycles](#def-g12-graph-algorithms-cycle) in an undirected [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph). code/grade-12/05-graph-algorithms/listings/cycle.py*

```python
def has_cycle_directed(g):
    colour = {v: WHITE for v in g}

    def explore(v):
        colour[v] = GREY
        for w in g[v]:
            if colour[w] == GREY:            # an edge back to a vertex in progress
                return True
            if colour[w] == WHITE and explore(w):
                return True
        colour[v] = BLACK
        return False

    return any(colour[v] == WHITE and explore(v) for v in g)


tree = {1: [2, 3], 2: [1, 4], 3: [1], 4: [2]}
square = {1: [2, 4], 2: [1, 3], 3: [2, 4], 4: [3, 1]}
print("tree:", has_cycle_undirected(tree), "| square:", has_cycle_undirected(square))
courses = {"maths": ["physics", "cs"], "physics": ["engineering"],
           "cs": ["engineering"], "engineering": []}
print("course prerequisites:", has_cycle_directed(courses))
courses["engineering"].append("maths")
print("with engineering -> maths:", has_cycle_directed(courses))
```

***Listing 26.4.** [Cycles](#def-g12-graph-algorithms-cycle) in a [directed graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed), with three colours; course prerequisites. code/grade-12/05-graph-algorithms/listings/cycle.py*

```
$ python cycle.py
tree: False | square: True
course prerequisites: False
with engineering -> maths: True
```

***Output 26.3.** A course that would require itself is a [cycle](#def-g12-graph-algorithms-cycle).*

## 26.3 Breadth-first search

**Method 26.4 (Breadth-first search).**

A *breadth-first search* from a vertex $s$ visits $s$, then all its neighbours, then all their unvisited neighbours, and so on, layer by layer. A queue holds the vertices found but not yet explored. Each vertex records its distance from $s$ in edges and its parent, the vertex from which it was found.

```python
from collections import deque

from representations import G


def bfs(g, start):
    """Distances in edges from start, and each vertex's parent on a shortest path."""
    dist, parent = {start: 0}, {start: None}
    line = deque([start])
    while line:
        v = line.popleft()
        for w in g[v]:
            if w not in dist:                # first time seen: by a shortest path
                dist[w] = dist[v] + 1
                parent[w] = v
                line.append(w)
    return dist, parent


def path_to(parent, target):
    path = []
    while target is not None:
        path.append(target)
        target = parent[target]
    return path[::-1]


if __name__ == "__main__":
    dist, parent = bfs(G, "A")
    print("distances:", dist)
    print("parents:  ", parent)
    print("a shortest path to F:", path_to(parent, "F"))
```

***Listing 26.5.** Breadth-first search: distances and parents. code/grade-12/05-graph-algorithms/listings/bfs.py*

```
$ python bfs.py
distances: {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}
parents:   {'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D'}
a shortest path to F: ['A', 'B', 'D', 'F']
```

***Output 26.4.** Following the parents back from F gives a shortest path.*

The queue gives back the vertices in order of distance: all those at distance $d$ before any at distance $d + 1$. So the first time a vertex is found, it is found by a shortest path (exercise [26.12](#exo-g12-graph-algorithms-12)). The parents form a tree, the breadth-first search tree, and the path from $s$ to any vertex in that tree is a shortest one.

A maze drawn on squared paper is a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph): each square is a vertex, and two squares are joined when no wall separates them.

![A small maze and the distances found by breadth-first search from the top-left square. Each number is one more than a neighbour’s that can be reached without crossing a wall; the darker the square, the closer.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-graph-algorithms/fig-b3e17b1b0f21.svg)

*A small maze and the distances found by breadth-first search from the top-left square. Each number is one more than a neighbour’s that can be reached without crossing a wall; the darker the square, the closer.*

The program below builds a maze of $8 \times 14$ squares by carving passages at random from a fixed seed, then knocks down twelve more walls so that some places can be reached in several ways. It finds the shortest way from the top-left square to the bottom-right one, and compares it with the hand on the wall.

```python
"""A seeded maze as a grid graph; its shortest exit and the hand-on-wall walk."""
import random

from bfs import bfs, path_to
from dfs import dfs_stack

ROWS, COLS = 8, 14
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # north, east, south, west


def make_maze(seed=12):
    rng = random.Random(seed)
    g = {(r, c): [] for r in range(ROWS) for c in range(COLS)}
    seen, stack = {(0, 0)}, [(0, 0)]
    while stack:                                     # carve a tree of passages
        r, c = stack[-1]
        fresh = [(r + dr, c + dc) for dr, dc in MOVES if (r + dr, c + dc) in g
                 and (r + dr, c + dc) not in seen]
        if not fresh:
            stack.pop()
            continue
        nxt = rng.choice(fresh)
        g[(r, c)].append(nxt)
        g[nxt].append((r, c))
        seen.add(nxt)
        stack.append(nxt)
    for _ in range(12):                              # then knock down 12 more walls
        r, c = rng.randrange(ROWS - 1), rng.randrange(COLS - 1)
        a, b = (r, c), rng.choice([(r + 1, c), (r, c + 1)])
        if b not in g[a]:
            g[a].append(b)
            g[b].append(a)
    return g


```

***Listing 26.6.** A maze as a grid [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), carved by a depth-first search. code/grade-12/05-graph-algorithms/listings/maze.py*

```python
def wall_follower(g, start, goal):
    """Keep the right hand on the wall; return the number of steps taken."""
    (r, c), facing, steps = start, 1, 0              # facing east
    while (r, c) != goal:
        for turn in (1, 0, 3, 2):                    # right, ahead, left, back
            d = (facing + turn) % 4
            nxt = (r + MOVES[d][0], c + MOVES[d][1])
            if nxt in g[(r, c)]:
                (r, c), facing, steps = nxt, d, steps + 1
                break
    return steps


if __name__ == "__main__":
    g = make_maze()
    start, goal = (0, 0), (ROWS - 1, COLS - 1)
    dist, parent = bfs(g, start)
    path = path_to(parent, goal)
    print(draw(g, marked=set(path)))
    print("shortest exit:", dist[goal], "steps")
    print("depth-first search visits", dfs_stack(g, start).index(goal) + 1,
          "cells before reaching the exit")
    print("hand on the wall:", wall_follower(g, start, goal), "steps")
```

***Listing 26.7.** The right hand on the wall, and the comparison. code/grade-12/05-graph-algorithms/listings/maze.py*

```
$ python maze.py
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| *|                 | *  *         |     |
+  +  +--+  +--+--+--+  +  +--+  +  +--+  +
| *|     |           | *| *  *  *|  |     |
+  +  +--+--+--+--+  +  +--+--+  +  +  +  +
| *|  | *  *  *  *  *| *|    *  *      |  |
+  +--+  +--+--+  +  +  +  +  +--+--+--+  +
| *  *  *|     |  | *  *|  | *|        |  |
+--+--+--+  +--+  +--+--+  +  +  +  +--+  +
|        |        |     |  | *|  |     |  |
+  +--+  +  +--+--+  +  +  +  +  +--+  +  +
|  |        |        |  |  | *   |  |     |
+  +  +--+  +  +  +--+  +  +  +--+  +  +--+
|  |     |  |  |  |  |       *  *| *  *|  |
+  +  +  +  +--+  +  +--+--+--+  +  +  +  +
|     |           |             *  *| *  *|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
shortest exit: 32 steps
depth-first search visits 92 cells before reaching the exit
hand on the wall: 58 steps
```

***Output 26.5.** The stars mark the shortest exit. Lines 36 to 47 of the file, not printed, draw the maze as text.*

## 26.4 Dijkstra’s algorithm

When edges have lengths, the path with fewest edges is not always the shortest: breadth-first search no longer answers. The [length of a path](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-path) is now the sum of the weights of its edges, all assumed positive or zero.

**Method 26.5 (Dijkstra’s algorithm).**

*Dijkstra’s algorithm* computes the distances from a source $s$ in a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) with weights $\ge 0$. It keeps a tentative distance for each vertex found, starting with $0$ for $s$, and a set of finished vertices, at first empty. At each step:

1. among the vertices found and not finished, pick one, $u$ , with the smallest tentative distance, and finish it;
2. for each edge from $u$ to an unfinished $v$ of weight $w$ , if $d(u) + w$ is smaller than the tentative distance of $v$ , or $v$ has none, set it to $d(u) + w$ , and record $u$ as the parent of $v$ .

It stops when every vertex found is finished.

**History — Dijkstra, 1959.**

Edsger W. Dijkstra published the method in 1959, in a three-page note titled “A note on two problems in connexion with [graphs](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph)”, in the first volume of the journal *Numerische Mathematik*.

```python
"""Dijkstra's algorithm, picking the closest unfinished vertex by a scan."""


def dijkstra(g, source, show=False):
    dist, parent, done = {source: 0}, {source: None}, set()
    while True:
        waiting = [v for v in dist if v not in done]
        if not waiting:
            return dist, parent
        u = min(waiting, key=lambda v: dist[v])     # its distance is now final
        done.add(u)
        for v, w in g[u].items():
            if v not in done and (v not in dist or dist[u] + w < dist[v]):
                dist[v] = dist[u] + w                # a shorter way to v, through u
                parent[v] = u
        if show:
            row = "  ".join(f"{v}:{dist[v]:>2}" if v in dist else f"{v}: -" for v in g)
            print(f"finish {u}   {row}")


W = {"S": {"A": 4, "B": 1}, "A": {"S": 4, "B": 2, "C": 5},
     "B": {"S": 1, "A": 2, "D": 8}, "C": {"A": 5, "D": 1, "T": 3},
     "D": {"B": 8, "C": 1, "T": 6}, "T": {"C": 3, "D": 6}}

if __name__ == "__main__":
    dist, parent = dijkstra(W, "S", show=True)
    path, v = [], "T"
    while v is not None:
        path, v = [v] + path, parent[v]
    print("distance S to T:", dist["T"], "| path:", " ".join(path))
```

***Listing 26.8.** [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra), with the minimum found by a scan. code/grade-12/05-graph-algorithms/listings/dijkstra.py*

```
$ python dijkstra.py
finish S   S: 0  A: 4  B: 1  C: -  D: -  T: -
finish B   S: 0  A: 3  B: 1  C: -  D: 9  T: -
finish A   S: 0  A: 3  B: 1  C: 8  D: 9  T: -
finish C   S: 0  A: 3  B: 1  C: 8  D: 9  T:11
finish D   S: 0  A: 3  B: 1  C: 8  D: 9  T:11
finish T   S: 0  A: 3  B: 1  C: 8  D: 9  T:11
distance S to T: 11 | path: S B A C T
```

***Output 26.6.** The tentative distances after each vertex is finished.*

![The graph W: each vertex with its final distance from S and the step at which it was finished. The bold edges join each vertex to its parent; they form the tree of shortest routes. D is at 9 through B and through C alike; the program keeps B, the first parent found, since it changes a parent only for a strictly shorter route. B is finished before A although S–A is a direct edge: through B, A is at 3, not 4.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-graph-algorithms/fig-30e40eb63ceb.svg)

*The [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) `W`: each vertex with its final distance from S and the step at which it was finished. The bold edges join each vertex to its parent; they form the tree of shortest routes. D is at $9$ through B and through C alike; the program keeps B, the first parent found, since it changes a parent only for a strictly shorter route. B is finished before A although S–A is a direct edge: through B, A is at $3$, not $4$.*

**Theorem 26.6 (The finished distances are final).**

With weights $\ge 0$, when [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) finishes a vertex, its tentative distance is its distance from $s$.

The idea of the proof (exercise [26.13](#exo-g12-graph-algorithms-13)): take a shortest path from $s$ to the vertex $u$ being finished, and the first vertex $y$ on it that is not yet finished. The vertex before $y$ is finished, and gave $y$ a tentative distance at most the length of the path up to $y$; that $d(y)$ is at least $d(u)$, since $u$ was picked as the smallest; and the rest of the path has weights $\ge 0$. So no path is shorter than $d(u)$. This version scans the unfinished vertices at each step: with $n$ vertices, $n$ steps of up to $n$ comparisons, a cost in $n^2$. A better structure for picking the minimum, met in a later volume, makes it much faster on large [graphs](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph).

Negative weights break the proof, and the algorithm:

```python
from itertools import permutations

from dijkstra import dijkstra

g = {"S": {"A": 1, "B": 3}, "A": {}, "B": {"A": -3}}   # B -> A costs -3


def brute_force(g, s, t):
    """Try every simple path from s to t: possible only on tiny graphs."""
    best = None
    others = [v for v in g if v not in (s, t)]
    for k in range(len(others) + 1):
        for middle in permutations(others, k):
            path = [s, *middle, t]
            if all(b in g[a] for a, b in zip(path, path[1:])):
                cost = sum(g[a][b] for a, b in zip(path, path[1:]))
                best = cost if best is None else min(best, cost)
    return best


print("Dijkstra: S to A =", dijkstra(g, "S")[0]["A"])
print("all paths: S to A =", brute_force(g, "S", "A"))
```

***Listing 26.9.** A negative weight, and every path tried by brute force. code/grade-12/05-graph-algorithms/listings/negative_weight.py*

```
$ python negative_weight.py
Dijkstra: S to A = 1
all paths: S to A = 0
```

***Output 26.7.** A finished at $1$, before the edge of weight $-3$ was seen.*

## 26.5 On the town

The town’s road [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) has $30$ places and $53$ roads, one of them one-way: road $1$ goes from the Town Square to the Library only. [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) from the Station gives the length of the shortest drive to every place.

```python
import csv

from dijkstra import dijkstra

with open("places.csv", newline="") as f:
    NAMES = {int(r["place_id"]): r["name"] for r in csv.DictReader(f)}
g = {p: {} for p in NAMES}
with open("roads.csv", newline="") as f:
    for r in csv.DictReader(f):
        a, b, metres = int(r["from_place"]), int(r["to_place"]), int(r["length_m"])
        g[a][b] = metres
        if r["one_way"] == "0":
            g[b][a] = metres

dist, parent = dijkstra(g, 2)                        # from the Station
far = sorted(dist, key=dist.get)
print("reached:", len(dist), "places | farthest:", NAMES[far[-1]], dist[far[-1]], "m")
for p in [1, 3, 4]:
    print(f"  Station -> {NAMES[p]:13} {dist[p]:>5} m")
there, back = dijkstra(g, 1)[0][3], dijkstra(g, 3)[0][1]
print(f"Town Square -> Library {there} m, Library -> Town Square {back} m")
```

***Listing 26.10.** Shortest drives from the Station. code/grade-12/05-graph-algorithms/listings/dijkstra_town.py*

```
$ python dijkstra_town.py
reached: 30 places | farthest: Bus Depot 4640 m
  Station -> Town Square    2970 m
  Station -> Library        4330 m
  Station -> North School   3900 m
Town Square -> Library 1360 m, Library -> Town Square 2630 m
```

***Output 26.8.** The one-way road makes the return from the Library almost twice as long.*

![The town’s roads (grey) and the tree of shortest routes from the Station (blue), drawn from the coordinates of the places by figures/town_tree.py; each place is labelled with its distance from the Station in kilometres.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-graph-algorithms/fig-824432e1662a.svg)

*The town’s roads (grey) and the tree of shortest routes from the Station (blue), drawn from the coordinates of the places by `figures/town_tree.py`; each place is labelled with its distance from the Station in kilometres.*

The functions above take a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) as a dictionary. A class can hide that dictionary behind methods; if it offers `g[v]` and a loop over the vertices, through two [special methods](https://one-course.com/books/computer-science/2/en/chapter/23-classes-and-objects#def-g12-classes-and-objects-special-method), the same `dijkstra` works on it unchanged.

```python
"""A graph as a class: the dictionary of dictionaries hidden behind methods."""


class Graph:
    def __init__(self):
        self._adj = {}

    def add_vertex(self, v):
        self._adj.setdefault(v, {})

    def add_edge(self, a, b, weight=1, directed=False):
        self.add_vertex(a)
        self.add_vertex(b)
        self._adj[a][b] = weight
        if not directed:
            self._adj[b][a] = weight

    def neighbours(self, v):
        return list(self._adj[v])

    def __iter__(self):                  # for v in graph: the vertices
        return iter(self._adj)

    def __getitem__(self, v):            # graph[v]: neighbour -> weight
        return dict(self._adj[v])

    def __len__(self):
        return len(self._adj)
```

***Listing 26.11.** A [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) class. code/grade-12/05-graph-algorithms/listings/graph_class.py*

```python
from dijkstra import dijkstra
from graph_class import Graph

g = Graph()
for a, b, w in [("S", "A", 4), ("S", "B", 1), ("A", "B", 2), ("A", "C", 5),
                ("B", "D", 8), ("C", "D", 1), ("C", "T", 3), ("D", "T", 6)]:
    g.add_edge(a, b, w)
g.add_edge("T", "X", 2, directed=True)
print(len(g), "vertices | neighbours of A:", g.neighbours("A"),
      "| of X:", g.neighbours("X"))
print("Dijkstra on the class:", dijkstra(g, "S")[0])
```

***Listing 26.12.** The [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) `W` rebuilt with the class, plus a one-way edge. code/grade-12/05-graph-algorithms/listings/use_graph.py*

```
$ python use_graph.py
7 vertices | neighbours of A: ['S', 'B', 'C'] | of X: []
Dijkstra on the class: {'S': 0, 'A': 3, 'B': 1, 'D': 9, 'C': 8, 'T': 11, 'X': 13}
```

***Output 26.9.** The same distances as before, and X reached through its one-way edge.*

## 26.6 Exercises

**Exercise 26.1 ★.**

Give the order of the recursive depth-first search of `G` from D.

**Solution of Exercise 26.1.**

D, B, A, C, E, F. From D, the first neighbour is B; from B, A; from A, C (B is visited); from C, E (A and D are visited); from E, F.

**Exercise 26.2 ★.**

Give the order of the breadth-first search of `G` from D, layer by layer.

**Solution of Exercise 26.2.**

Layer $0$: D. Layer $1$: B, C, F. Layer $2$: A (found from B), E (found from C). The order is D, B, C, F, A, E.

**Exercise 26.3 ★.**

Four vertices $1$, $2$, $3$, $4$ form a square, $1$–$2$–$3$–$4$–$1$, with one diagonal $1$–$3$. Write its adjacency matrix and its [adjacency lists](#def-g12-graph-algorithms-adjacency-list).

**Solution of Exercise 26.3.**

Rows and columns in the order $1$ to $4$:

$$
\begin{pmatrix} 0 & 1 & 1 & 1 \\ 1 & 0 & 1 & 0 \\ 1 & 1 & 0 & 1 \\ 1 & 0 & 1 & 0 \end{pmatrix}
$$

and the lists `{1: [2, 3, 4], 2: [1, 3], 3: [1, 2, 4], 4: [1, 3]}`.

**Exercise 26.4 ★.**

Give the distances in edges from E to every vertex of `G`.

**Solution of Exercise 26.4.**

E $0$; C and F $1$; A and D $2$; B $3$.

**Exercise 26.5 ★.**

Write `count_edges(adj)`, the number of edges of an undirected [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) given by [adjacency lists](#def-g12-graph-algorithms-adjacency-list).

**Solution of Exercise 26.5.**

    `def count_edges(adj):`

        `return sum(len(ns) for ns in adj.values()) // 2`

Each edge appears in the lists of both its ends: $14 / 2 = 7$ for `G`.

**Exercise 26.6 ★★.**

A student’s search marks a vertex when it enters it and unmarks it when it returns, “to keep the marks clean”. On a grid of $4 \times 4$ squares, it makes $2111$ calls from a corner. How many does the depth-first search of the chapter make, and why does the student’s version make so many?

**Solution of Exercise 26.6.**

$16$: one call per square, since a square once marked is never entered again. The student’s version unmarks a square when it returns, so the square can be entered again along another path: it walks every path from the corner that never crosses itself. Their number grows very fast with the size of the grid: $7$, $79$ and $2111$ calls for the grids of $2 \times 2$, $3 \times 3$ and $4 \times 4$ squares.

**Exercise 26.7 ★★.**

Write `has_path(g, a, b)`, which stops as soon as `b` is found.

**Solution of Exercise 26.7.**

    `def has_path(g, a, b):`

        `seen, stack = {a}, [a]`

        `while stack:`

            `v = stack.pop()`

            `if v == b:`

                `return True`

            `for w in g[v]:`

                `if w not in seen:`

                    `seen.add(w)`

                    `stack.append(w)`

        `return False`

**Exercise 26.8 ★★.**

Run [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) by hand on `W` from A: the vertex finished at each step and the tentative distances.

**Solution of Exercise 26.8.**

Finish A ($0$): S $4$, B $2$, C $5$. Finish B ($2$): S becomes $3$, D $10$. Finish S ($3$): nothing changes. Finish C ($5$): D becomes $6$, T $8$. Finish D ($6$), then T ($8$). Distances from A: S $3$, B $2$, C $5$, D $6$, T $8$.

**Exercise 26.9 ★★.**

A version of [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) finishes, at each step, the vertex found last instead of the closest. On `W` from S it gives $15$ for T. Find where it goes wrong.

**Solution of Exercise 26.9.**

After S, it finishes B, the last found, at $1$: correct by luck. A drops to $3$ and D gets $9$; it finishes D, the last found, although A, at $3$, is closer. From D, C gets $10$ and T $15$. It then finishes T at $15$, while the route S, B, A, C, T of length $11$ is not yet known, and C at $10$ instead of $8$. Finishing a vertex declares its distance final, which is only safe for the closest unfinished vertex.

**Exercise 26.10 ★★.**

The town has $30$ places and $53$ roads, one of them one-way. How many entries do its [adjacency lists](#def-g12-graph-algorithms-adjacency-list) hold, and how many cells its adjacency matrix?

**Solution of Exercise 26.10.**

The lists hold one entry per direction of each road: $52 \times 2 + 1 = 105$ entries, plus the $30$ places. The matrix has $30 \times 30 = 900$ cells, of which $795$ are $0$.

**Exercise 26.11 ★★.**

Write `bfs_layers(g, s)`, which returns the list of layers: `[[s], [vertices at distance 1], ...]`.

**Solution of Exercise 26.11.**

    `def bfs_layers(g, s):`

        `layers, seen = [[s]], {s}`

        `while True:`

            `nxt = []`

            `for v in layers[-1]:`

                `for w in g[v]:`

                    `if w not in seen:`

                        `seen.add(w)`

                        `nxt.append(w)`

            `if not nxt:`

                `return layers`

            `layers.append(nxt)`

No queue is needed: each layer is built from the one before. For `G` from D: `[['D'], ['B', 'C', 'F'], ['A', 'E']]`.

**Exercise 26.12 ★★★.**

Prove that breadth-first search gives every reachable vertex its distance in edges from $s$.

**Solution of Exercise 26.12.**

Write $\delta(v)$ for the true distance and $d(v)$ for the number the search records.

First, $d(v) \ge \delta(v)$: following the parents from $v$ gives a real path of $d(v)$ edges.

Next, the queue: we show by induction on the steps that its numbers, from front to back, never decrease and differ by at most $1$. A step removes the front vertex $v$, of number $d$, and appends vertices numbered $d + 1$; since every number left was between $d$ and $d + 1$, the property is kept. So the vertices leave the queue in increasing order of their numbers.

Finally, $d(v) \le \delta(v)$, by induction on $k = \delta(v)$. For $k = 0$, $v = s$. If $\delta(v) = k \ge 1$, let $u$ be the vertex before $v$ on a shortest path: $\delta(u) = k - 1$, so $d(u) = k - 1$ by induction, and $u$ goes through the queue. When $u$ is removed, $v$ is numbered, either now as $d(u) + 1 = k$, or earlier by a vertex $x$ removed before $u$, with $d(x) \le d(u)$, so $d(v) = d(x) + 1 \le k$. Hence $d(v) = \delta(v)$.

**Exercise 26.13 ★★★.**

Prove the theorem on [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra).

**Solution of Exercise 26.13.**

By induction on the steps: assume every vertex finished so far has its true distance, and let $u$ be the next one, with tentative distance $d(u)$. Tentative distances are lengths of real paths, so $d(u) \ge \delta(u)$. Take any path $P$ from $s$ to $u$. It starts at a finished vertex and ends at an unfinished one: let $y$ be its first unfinished vertex, and $x$ the vertex just before it, finished. When $x$ was finished, its edge to $y$ was examined, so $d(y) \le \delta(x) + w(x, y)$, which is the length of $P$ up to $y$. Then $d(u) \le d(y)$, since $u$ has the smallest tentative distance; and the rest of $P$, from $y$ to $u$, has weights $\ge 0$. So the length of $P$ is at least $d(y) \ge d(u)$. This holds for every path: $\delta(u) \ge d(u)$, and $d(u) = \delta(u)$. The step “rest of $P$ is $\ge 0$” is exactly where negative weights break the proof.

**Exercise 26.14 ★★★.**

Write `topological_order(g)`, which orders the vertices of a [directed graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed) so that every edge goes from an earlier vertex to a later one, and raises `ValueError` if the [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) has a [cycle](#def-g12-graph-algorithms-cycle).

**Solution of Exercise 26.14.**

    `def topological_order(g):`

        `state, order = {v: 0 for v in g}, []`

        `def explore(v):`

            `state[v] = 1`

            `for w in g[v]:`

                `if state[w] == 1:`

                    `raise ValueError("the graph has a cycle")`

                `if state[w] == 0:`

                    `explore(w)`

            `state[v] = 2`

            `order.append(v)`

        `for v in g:`

            `if state[v] == 0:`

                `explore(v)`

        `return order[::-1]`

The three states are the three colours. A vertex is appended once all its [successors](#def-g12-graph-algorithms-adjacency-list) are, so in the reversed list it comes before them. The tests compare it with every order of small random [graphs](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph).

**Exercise 26.15 ★★★.**

To remove negative weights, a student adds the same number to every weight, then runs [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra). Show with the [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) of `negative_weight.py` that the path found is not the shortest in the original [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph).

**Solution of Exercise 26.15.**

Add $3$: S–A weighs $4$, S–B $6$, B–A $0$. [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) finds S to A $= 4$ by the direct edge, against $6$ through B; in the original [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) that direct path costs $1$, but the path through B costs $0$. Adding $3$ to each edge adds $3$ times the number of edges to each path: paths with more edges are penalised more, and the order of the paths changes.

## 26.7 Problem: The Shortest Exit

**Problem 26.1.**

Weekend problem — the shortest exit

The maze of `maze.py` has $8 \times 14$ squares, an entrance at the top-left square and an exit at the bottom-right one. In its second version, $30$ of its passages, chosen at random, are doors that take $6$ seconds to cross instead of $1$.

```python
"""The same maze, where some passages are doors that take 6 seconds to open."""
import random

from bfs import bfs, path_to
from dijkstra import dijkstra
from maze import COLS, ROWS, make_maze

maze = make_maze()
rng = random.Random(5)
passages = sorted({tuple(sorted((a, b))) for a in maze for b in maze[a]})
doors = set(rng.sample(passages, 30))
g = {a: {b: 6 if tuple(sorted((a, b))) in doors else 1 for b in maze[a]} for a in maze}

start, goal = (0, 0), (ROWS - 1, COLS - 1)
short = path_to(bfs(maze, start)[1], goal)
cost_short = sum(g[a][b] for a, b in zip(short, short[1:]))
dist, parent = dijkstra(g, start)
cheap = path_to(parent, goal)
print(len(passages), "passages,", len(doors), "of them doors")
print(f"fewest steps: {len(short) - 1} steps, {cost_short} seconds")
print(f"fastest:      {len(cheap) - 1} steps, {dist[goal]} seconds")
```

***Listing 26.13.** The maze with doors. code/grade-12/05-graph-algorithms/listings/maze_doors.py*

```
$ python maze_doors.py
119 passages, 30 of them doors
fewest steps: 32 steps, 57 seconds
fastest:      34 steps, 54 seconds
```

***Output 26.10.** The path with fewest steps is not the fastest.*

**Part I — A maze as a graph.**

1. What are the vertices and the edges of the maze’s [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) ? How many vertices?
2. The carving makes a tree of passages. How many passages does it open? How many does the program count in the end, and why?
3. In `make_maze` , which structure of the chapter does `stack` implement, and which search does the carving perform?
4. Why does the maze have several routes from the entrance to the exit, and not just one?

**Part II — Searching for the exit.**

5. How many squares does the depth-first search visit before it reaches the exit? Why so many?
6. Explain the order of the four turns in `wall_follower` .
7. How many steps does the hand on the wall take? Why more than the shortest exit?
8. Why is the hand on the wall sure to reach the exit here, although the maze has loops?
9. Which information does the wall follower keep, and which does a search keep?

**Part III — The shortest exit.**

10. How long is the shortest exit? Check it on the drawing by counting the stars.
11. Why is the path built from the parents a shortest one?
12. Is it the only shortest exit? How would you find out?

**Part IV — Doors.**

13. How are the doors stored in the [weighted graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed) `g` ?
14. Why can breadth-first search not find the fastest exit?
15. How long does the fewest-steps exit take, and how many doors does it cross?
16. How long is the fastest exit, in steps and in seconds, and how many doors does it cross?
17. Why is [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) correct here?
18. If every door took $1$ second, what would the fastest exit cost?
19. With $n$ squares, what is the cost of the scan version of [Dijkstra’s algorithm](#met-g12-graph-algorithms-dijkstra) , and is it acceptable here?
20. State the result: the shortest exit against the hand on the wall, and the fastest exit with doors.

**Solution of Problem 26.1.**

**1.** The vertices are the $8 \times 14 = 112$ squares; an edge joins two squares side by side with no wall between them.

**2.** A tree on $112$ vertices has $111$ edges: $111$ passages. The program counts $119$: of the twelve walls picked afterwards, eight were real walls, and four were already open passages, which the test `if b not in g[a]` skips.

**3.** A stack: the carving is a depth-first search, which at each step goes to a random unvisited neighbour, and backs up from dead ends.

**4.** The eight extra passages each close a loop in the tree, giving a second route between the squares they join.

**5.** $92$ squares out of $112$. Depth-first search follows its neighbours in a fixed order, deep into whatever branch comes first, with no idea where the exit is: it reaches the exit only when that branch’s turn comes.

**6.** Right first: as long as the wall on the right has an opening, the walker turns into it, so its right hand never leaves the wall. Ahead if the right is closed, then left, and back only in a dead end.

**7.** $58$ steps, against $32$: it walks into every dead end that opens on its right side, and back out.

**8.** The entrance is a corner square, so the walls around it belong to the outer wall and the walls joined to it, one connected group of walls; the walker keeps its hand on that group, which runs all the way round the maze and past the exit square, also on the outer wall. The loops create walls standing alone inside the maze, and only a walker started beside one of them could circle for ever.

**9.** The wall follower keeps only its square and the direction it faces. A search keeps the set of visited squares and its stack or queue, a memory that grows with the maze.

**10.** $32$ steps: $33$ stars, the entrance and the exit included.

**11.** Each parent is one step closer to the entrance (exercise [26.12](#exo-g12-graph-algorithms-12)): following them back from the exit takes $32$ steps, the distance.

**12.** Not necessarily. Counting them layer by layer, each square has as many shortest routes as the sum of those of its neighbours one layer closer; the tests run this count on the maze and find $5$ shortest exits.

**13.** As weights: `g[a][b]` is $6$ when the passage between $a$ and $b$ is a door, $1$ otherwise, in both directions.

**14.** It counts edges as if they all cost the same; here a door costs six times an open passage.

**15.** $32$ steps, $57$ seconds: $57 = 32 + 5 \times 5$, so $5$ doors.

**16.** $34$ steps, $54$ seconds: $54 = 34 + 4 \times 5$, so $4$ doors. Two more steps avoid one door.

**17.** All weights, $1$ and $6$, are positive: the theorem applies.

**18.** $32$ seconds: every step costs $1$, and the fastest exit is the one with fewest steps.

**19.** $n = 112$: at most $112^2 = 12\,544$ comparisons, nothing for a computer.

**20.** **The shortest exit of the maze takes $32$ steps, where the hand on the wall takes $58$ (and the depth-first search visits $92$ squares); with doors, the fastest exit takes $54$ seconds in $34$ steps, against $57$ seconds for the exit with fewest steps.**
