এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
High School Computer Science · শ্রেণি 10–12
26Graph 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, depth first with a stack and breadth first with a queue, and uses them to decide what can be reached, to find cycles and to find shortest paths counted in edges. Then the edges get lengths, and Dijkstra’s algorithm finds the shortest routes across the town.
You already know
A 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 were defined in chapter 9, where the town’s road graph was first loaded. A stack gives back its newest element first, a queue its oldest (chapter 24). The adjacency matrix of a graph (the mathematics book).
26.1 Representations
Definition 26.1 (Adjacency list, successor, predecessor)
The adjacency lists of a graph give, for each vertex, the list of its neighbours; in Python, a dictionary from each vertex to that list. In a directed graph, the vertices at the end of the edges leaving are its successors, and those at the start of the edges arriving at its predecessors; the lists usually give the successors.
The adjacency matrix of a graph of vertices is an table of and , with a in row and column when there is an edge from to .
"""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)
$ 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']}
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.The two cost differently. The matrix always takes cells, and answers “is there an edge from to ?” in one step. The lists take one entry per edge end, and list the neighbours of without looking at the others. For a town of places and roads the lists are far smaller; most graphs 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 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 can play that role.
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")))
$ 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']
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 visits exactly the vertices reachable from ; 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, it has at least three vertices.
In an undirected graph, a depth-first search that meets an already visited vertex, other than the one it came from, has found a cycle. In a directed graph that is not enough: two paths may join without any 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 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
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))
$ python cycle.py
tree: False | square: True
course prerequisites: False
with engineering -> maths: True
26.3 Breadth-first search
Method 26.4 (Breadth-first search)
A breadth-first search from a vertex visits , 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 in edges and its parent, the vertex from which it was found.
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"))
$ 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']
The queue gives back the vertices in order of distance: all those at distance before any at distance . So the first time a vertex is found, it is found by a shortest path (exercise 26.12). The parents form a tree, the breadth-first search tree, and the path from to any vertex in that tree is a shortest one.
A maze drawn on squared paper is a graph: each square is a vertex, and two squares are joined when no wall separates them.
The program below builds a maze of 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.
"""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
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")
$ python maze.py
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| *| | * * | |
+ + +--+ +--+--+--+ + +--+ + +--+ +
| *| | | *| * * *| | |
+ + +--+--+--+--+ + +--+--+ + + + +
| *| | * * * * *| *| * * | |
+ +--+ +--+--+ + + + + +--+--+--+ +
| * * *| | | * *| | *| | |
+--+--+--+ +--+ +--+--+ + + + +--+ +
| | | | | *| | | |
+ +--+ + +--+--+ + + + + +--+ + +
| | | | | | * | | |
+ + +--+ + + +--+ + + +--+ + +--+
| | | | | | | * *| * *| |
+ + + + +--+ + +--+--+--+ + + + +
| | | * *| * *|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
shortest exit: 32 steps
depth-first search visits 92 cells before reaching the exit
hand on the wall: 58 steps
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 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 in a graph with weights . It keeps a tentative distance for each vertex found, starting with for , and a set of finished vertices, at first empty. At each step:
- among the vertices found and not finished, pick one, , with the smallest tentative distance, and finish it;
- for each edge from to an unfinished of weight , if is smaller than the tentative distance of , or has none, set it to , and record as the parent of .
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”, in the first volume of the journal Numerische Mathematik.
"""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))
$ 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
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 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 , not .Theorem 26.6 (The finished distances are final)
With weights , when Dijkstra’s algorithm finishes a vertex, its tentative distance is its distance from .
The idea of the proof (exercise 26.13): take a shortest path from to the vertex being finished, and the first vertex on it that is not yet finished. The vertex before is finished, and gave a tentative distance at most the length of the path up to ; that is at least , since was picked as the smallest; and the rest of the path has weights . So no path is shorter than . This version scans the unfinished vertices at each step: with vertices, steps of up to comparisons, a cost in . A better structure for picking the minimum, met in a later volume, makes it much faster on large graphs.
Negative weights break the proof, and the algorithm:
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"))
$ python negative_weight.py
Dijkstra: S to A = 1
all paths: S to A = 0
26.5 On the town
The town’s road graph has places and roads, one of them one-way: road goes from the Town Square to the Library only. Dijkstra’s algorithm from the Station gives the length of the shortest drive to every place.
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")
$ 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
figures/town_tree.py; each place is labelled with its distance from the Station in kilometres.The functions above take a 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, the same dijkstra works on it unchanged.
"""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)
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])
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}
26.6 Exercises
Exercise 26.1 ★
Give the order of the recursive depth-first search of G from D.
Solution
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
Solution of Exercise 26.2.
Layer : D. Layer : B, C, F. Layer : A (found from B), E (found from C). The order is D, B, C, F, A, E.
Exercise 26.3 ★
Four vertices , , , form a square, ––––, with one diagonal –. Write its adjacency matrix and its adjacency lists.
Solution
Solution of Exercise 26.3.
Rows and columns in the order to :
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
Solution of Exercise 26.4.
E ; C and F ; A and D ; B .
Exercise 26.5 ★
Write count_edges(adj), the number of edges of an undirected graph given by adjacency lists.
Solution
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: 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 squares, it makes 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
Solution of Exercise 26.6.
: 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: , and calls for the grids of , and squares.
Exercise 26.7 ★★
Write has_path(g, a, b), which stops as soon as b is found.
Solution
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 by hand on W from A: the vertex finished at each step and the tentative distances.
Solution
Solution of Exercise 26.8.
Finish A (): S , B , C . Finish B (): S becomes , D . Finish S (): nothing changes. Finish C (): D becomes , T . Finish D (), then T (). Distances from A: S , B , C , D , T .
Exercise 26.9 ★★
A version of Dijkstra’s algorithm finishes, at each step, the vertex found last instead of the closest. On W from S it gives for T. Find where it goes wrong.
Solution
Solution of Exercise 26.9.
After S, it finishes B, the last found, at : correct by luck. A drops to and D gets ; it finishes D, the last found, although A, at , is closer. From D, C gets and T . It then finishes T at , while the route S, B, A, C, T of length is not yet known, and C at instead of . Finishing a vertex declares its distance final, which is only safe for the closest unfinished vertex.
Exercise 26.10 ★★
The town has places and roads, one of them one-way. How many entries do its adjacency lists hold, and how many cells its adjacency matrix?
Solution
Solution of Exercise 26.10.
The lists hold one entry per direction of each road: entries, plus the places. The matrix has cells, of which are .
Exercise 26.11 ★★
Write bfs_layers(g, s), which returns the list of layers: [[s], [vertices at distance 1], ...].
Solution
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 .
Solution
Solution of Exercise 26.12.
Write for the true distance and for the number the search records.
First, : following the parents from gives a real path of 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 . A step removes the front vertex , of number , and appends vertices numbered ; since every number left was between and , the property is kept. So the vertices leave the queue in increasing order of their numbers.
Finally, , by induction on . For , . If , let be the vertex before on a shortest path: , so by induction, and goes through the queue. When is removed, is numbered, either now as , or earlier by a vertex removed before , with , so . Hence .
Exercise 26.13 ★★★
Prove the theorem on Dijkstra’s algorithm.
Solution
Solution of Exercise 26.13.
By induction on the steps: assume every vertex finished so far has its true distance, and let be the next one, with tentative distance . Tentative distances are lengths of real paths, so . Take any path from to . It starts at a finished vertex and ends at an unfinished one: let be its first unfinished vertex, and the vertex just before it, finished. When was finished, its edge to was examined, so , which is the length of up to . Then , since has the smallest tentative distance; and the rest of , from to , has weights . So the length of is at least . This holds for every path: , and . The step “rest of is ” is exactly where negative weights break the proof.
Exercise 26.14 ★★★
Write topological_order(g), which orders the vertices of a directed graph so that every edge goes from an earlier vertex to a later one, and raises ValueError if the graph has a cycle.
Solution
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 are, so in the reversed list it comes before them. The tests compare it with every order of small random graphs.
Exercise 26.15 ★★★
To remove negative weights, a student adds the same number to every weight, then runs Dijkstra’s algorithm. Show with the graph of negative_weight.py that the path found is not the shortest in the original graph.
Solution
Solution of Exercise 26.15.
Add : S–A weighs , S–B , B–A . Dijkstra’s algorithm finds S to A by the direct edge, against through B; in the original graph that direct path costs , but the path through B costs . Adding to each edge adds 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 squares, an entrance at the top-left square and an exit at the bottom-right one. In its second version, of its passages, chosen at random, are doors that take seconds to cross instead of .
"""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")
$ python maze_doors.py
119 passages, 30 of them doors
fewest steps: 32 steps, 57 seconds
fastest: 34 steps, 54 seconds
Part I — A maze as a graph.
- What are the vertices and the edges of the maze’s graph? How many vertices?
- The carving makes a tree of passages. How many passages does it open? How many does the program count in the end, and why?
- In
make_maze, which structure of the chapter doesstackimplement, and which search does the carving perform? - Why does the maze have several routes from the entrance to the exit, and not just one?
Part II — Searching for the exit.
- How many squares does the depth-first search visit before it reaches the exit? Why so many?
- Explain the order of the four turns in
wall_follower. - How many steps does the hand on the wall take? Why more than the shortest exit?
- Why is the hand on the wall sure to reach the exit here, although the maze has loops?
- Which information does the wall follower keep, and which does a search keep?
Part III — The shortest exit.
- How long is the shortest exit? Check it on the drawing by counting the stars.
- Why is the path built from the parents a shortest one?
- Is it the only shortest exit? How would you find out?
Part IV — Doors.
- How are the doors stored in the weighted graph
g? - Why can breadth-first search not find the fastest exit?
- How long does the fewest-steps exit take, and how many doors does it cross?
- How long is the fastest exit, in steps and in seconds, and how many doors does it cross?
- Why is Dijkstra’s algorithm correct here?
- If every door took second, what would the fastest exit cost?
- With squares, what is the cost of the scan version of Dijkstra’s algorithm, and is it acceptable here?
- State the result: the shortest exit against the hand on the wall, and the fastest exit with doors.
Solution
Solution of Problem 26.1.
1. The vertices are the squares; an edge joins two squares side by side with no wall between them.
2. A tree on vertices has edges: passages. The program counts : 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. squares out of . 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. steps, against : 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. steps: stars, the entrance and the exit included.
11. Each parent is one step closer to the entrance (exercise 26.12): following them back from the exit takes 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 shortest exits.
13. As weights: g[a][b] is when the passage between and is a door, 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. steps, seconds: , so doors.
16. steps, seconds: , so doors. Two more steps avoid one door.
17. All weights, and , are positive: the theorem applies.
18. seconds: every step costs , and the fastest exit is the one with fewest steps.
19. : at most comparisons, nothing for a computer.
20. The shortest exit of the maze takes steps, where the hand on the wall takes (and the depth-first search visits squares); with doors, the fastest exit takes seconds in steps, against seconds for the exit with fewest steps.