কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 vv are its successors, and those at the start of the edges arriving at vv its predecessors; the lists usually give the successors.

The adjacency matrix of a graph of nn vertices is an n×nn \times n table of 00 and 11, with a 11 in row vv and column ww when there is an edge from vv to ww.

"""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 of a directed graph. 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.
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.

The two cost differently. The matrix always takes n2n^2 cells, and answers “is there an edge from vv to ww?” in one step. The lists take one entry per edge end, and list the neighbours of vv without looking at the others. For a town of 3030 places and 5353 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")))
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.
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 vv visits exactly the vertices reachable from vv; 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

Listing 26.3. Cycles in an undirected graph. code/grade-12/05-graph-algorithms/listings/cycle.py
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 in a directed graph, 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.

26.3 Breadth-first search

Method 26.4 (Breadth-first search)

A breadth-first search from a vertex ss visits ss, 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 ss 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"))
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 dd before any at distance d+1d + 1. 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 ss 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.

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.
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×148 \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.

"""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, carved by a depth-first search. code/grade-12/05-graph-algorithms/listings/maze.py
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 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 ss in a graph with weights ≥0\ge 0. It keeps a tentative distance for each vertex found, starting with 00 for ss, and a set of finished vertices, at first empty. At each step:

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

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))
Listing 26.8. Dijkstra’s algorithm, 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.
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 99 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 33, not 44.

Theorem 26.6 (The finished distances are final)

With weights ≥0\ge 0, when Dijkstra’s algorithm finishes a vertex, its tentative distance is its distance from ss.

The idea of the proof (exercise 26.13): take a shortest path from ss to the vertex uu being finished, and the first vertex yy on it that is not yet finished. The vertex before yy is finished, and gave yy a tentative distance at most the length of the path up to yy; that d(y)d(y) is at least d(u)d(u), since uu was picked as the smallest; and the rest of the path has weights ≥0\ge 0. So no path is shorter than d(u)d(u). This version scans the unfinished vertices at each step: with nn vertices, nn steps of up to nn comparisons, a cost in n2n^2. 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"))
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 11, before the edge of weight −3-3 was seen.

26.5 On the town

The town’s road graph has 3030 places and 5353 roads, one of them one-way: road 11 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")
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.
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 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)
Listing 26.11. A graph class. code/grade-12/05-graph-algorithms/listings/graph_class.py
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 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

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 00: D. Layer 11: B, C, F. Layer 22: A (found from B), E (found from C). The order is D, B, C, F, A, E.

Exercise 26.3 ★

Four vertices 11, 22, 33, 44 form a square, 11–22–33–44–11, with one diagonal 11–33. Write its adjacency matrix and its adjacency lists.

Solution

Solution of Exercise 26.3.

Rows and columns in the order 11 to 44:

(0111101011011010)\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

Solution of Exercise 26.4.

E 00; C and F 11; A and D 22; B 33.

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: 14/2=714 / 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×44 \times 4 squares, it makes 21112111 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.

1616: 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: 77, 7979 and 21112111 calls for the grids of 2×22 \times 2, 3×33 \times 3 and 4×44 \times 4 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 (00): S 44, B 22, C 55. Finish B (22): S becomes 33, D 1010. Finish S (33): nothing changes. Finish C (55): D becomes 66, T 88. Finish D (66), then T (88). Distances from A: S 33, B 22, C 55, D 66, T 88.

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 1515 for T. Find where it goes wrong.

Solution

Solution of Exercise 26.9.

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

Exercise 26.10 ★★

The town has 3030 places and 5353 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: 52×2+1=10552 \times 2 + 1 = 105 entries, plus the 3030 places. The matrix has 30×30=90030 \times 30 = 900 cells, of which 795795 are 00.

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 ss.

Solution

Solution of Exercise 26.12.

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

First, d(v)≥δ(v)d(v) \ge \delta(v): following the parents from vv gives a real path of d(v)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 11. A step removes the front vertex vv, of number dd, and appends vertices numbered d+1d + 1; since every number left was between dd and d+1d + 1, the property is kept. So the vertices leave the queue in increasing order of their numbers.

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

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 uu be the next one, with tentative distance d(u)d(u). Tentative distances are lengths of real paths, so d(u)≥δ(u)d(u) \ge \delta(u). Take any path PP from ss to uu. It starts at a finished vertex and ends at an unfinished one: let yy be its first unfinished vertex, and xx the vertex just before it, finished. When xx was finished, its edge to yy was examined, so d(y)≤δ(x)+w(x,y)d(y) \le \delta(x) + w(x, y), which is the length of PP up to yy. Then d(u)≤d(y)d(u) \le d(y), since uu has the smallest tentative distance; and the rest of PP, from yy to uu, has weights ≥0\ge 0. So the length of PP is at least d(y)≥d(u)d(y) \ge d(u). This holds for every path: δ(u)≥d(u)\delta(u) \ge d(u), and d(u)=δ(u)d(u) = \delta(u). The step “rest of PP is ≥0\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 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 33: S–A weighs 44, S–B 66, B–A 00. Dijkstra’s algorithm finds S to A =4= 4 by the direct edge, against 66 through B; in the original graph that direct path costs 11, but the path through B costs 00. Adding 33 to each edge adds 33 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×148 \times 14 squares, an entrance at the top-left square and an exit at the bottom-right one. In its second version, 3030 of its passages, chosen at random, are doors that take 66 seconds to cross instead of 11.

"""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? 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.

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

Part III — The shortest exit.

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

Part IV — Doors.

  1. How are the doors stored in the weighted graph g?
  2. Why can breadth-first search not find the fastest exit?
  3. How long does the fewest-steps exit take, and how many doors does it cross?
  4. How long is the fastest exit, in steps and in seconds, and how many doors does it cross?
  5. Why is Dijkstra’s algorithm correct here?
  6. If every door took 11 second, what would the fastest exit cost?
  7. With nn squares, what is the cost of the scan version of Dijkstra’s algorithm, and is it acceptable here?
  8. 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 8×14=1128 \times 14 = 112 squares; an edge joins two squares side by side with no wall between them.

2. A tree on 112112 vertices has 111111 edges: 111111 passages. The program counts 119119: 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. 9292 squares out of 112112. 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. 5858 steps, against 3232: 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. 3232 steps: 3333 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 3232 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 55 shortest exits.

13. As weights: g[a][b] is 66 when the passage between aa and bb is a door, 11 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. 3232 steps, 5757 seconds: 57=32+5×557 = 32 + 5 \times 5, so 55 doors.

16. 3434 steps, 5454 seconds: 54=34+4×554 = 34 + 4 \times 5, so 44 doors. Two more steps avoid one door.

17. All weights, 11 and 66, are positive: the theorem applies.

18. 3232 seconds: every step costs 11, and the fastest exit is the one with fewest steps.

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

20. The shortest exit of the maze takes 3232 steps, where the hand on the wall takes 5858 (and the depth-first search visits 9292 squares); with doors, the fastest exit takes 5454 seconds in 3434 steps, against 5757 seconds for the exit with fewest steps.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো