Python 3D Academyবাংলা

Breadth-first search: the fewest steps

🌍 In real life. Drop a stone in a pond. The first ring of ripples reaches everything one step away, the next ring everything two steps away, and so on. Nothing two steps away is reached before everything one step away.

Ask "what is the fewest number of roads from town A to town F?" and that ripple is the answer. Breadth-first search spreads out from the start exactly like it: first all the neighbours, then all of their new neighbours, ring by ring. The ring where a town is first reached is its distance. It is the same queue idea as a tree's level order (Lesson 47.3), with one addition: a graph can loop back, so we must remember who has already been seen.

The idea in one sentence: BFS keeps a queue of vertices to process and a record of every vertex already seen; it takes the front vertex and gives each neighbour not yet seen a distance one more than its own, putting it at the back, so vertices come out in order of distance.

Its words:

  • distance: the fewest edges on any path from the start (in an unweighted graph)
  • seen (or visited): vertices already given a distance; checked so nobody joins the queue twice
  • frontier: the vertices waiting in the queue
  • BFS tree: for each vertex, the edge it was first reached by; following those back gives a shortest path
  • parent: the vertex a vertex was first reached from

How it works, step by step:

  1. give the start distance 0 and put it in the queue
  2. while the queue is not empty, take the vertex v at its front
  3. for each neighbour w of v that has not been seen: its distance is v's + 1; remember v as its parent; put it at the back
  4. when the queue is empty, every reachable vertex has its distance

Watch the ripple spread from A: the distances appear under each town, and the gold edges are the shortest roads:

Why it is correct. The queue always holds vertices of at most two neighbouring distances, d and d + 1, with all the d's in front. That is true at the start (just the start, distance 0). Taking a vertex of distance d only adds vertices of distance d + 1 at the back, so it stays true. So vertices leave the queue in order of distance. A vertex w first gets its distance from the earliest neighbour to leave, and that neighbour is as close to the start as any of w's neighbours, so no shorter route to w can exist. Marking a vertex when it is first seen (not when it leaves) also stops it joining the queue twice.

What it costs, by counting. Each vertex joins and leaves the queue once, and each edge is looked at from both ends once: O(V + E) time, and O(V) memory for the queue and the distances. For the six towns that is 6 vertices and 12 neighbour checks. BFS gives the fewest edges; when roads have different lengths, the fewest edges is not the shortest drive, and Chapter 54's Dijkstra is needed.

from collections import deque

def bfs_distances(graph, start):
    dist = {start: 0}
    queue = deque([start])
    while queue:
        v = queue.popleft()
        for w in graph[v]:
            if w not in dist:            # mark when first seen, not when taken out
                dist[w] = dist[v] + 1
                queue.append(w)
    return dist

towns = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"], "D": ["B", "C", "F"], "E": ["C"], "F": ["D"]}
print(sorted(bfs_distances(towns, "A").items()))

from collections import deque

def shortest_path(graph, start, goal):
    parent = {start: None}
    queue = deque([start])
    while queue:
        v = queue.popleft()
        if v == goal:
            path = []
            while v is not None:         # walk back along the parents
                path.append(v)
                v = parent[v]
            return path[::-1]
        for w in graph[v]:
            if w not in parent:
                parent[w] = v
                queue.append(w)
    return []

print(shortest_path(towns, "A", "F"))
print(shortest_path(towns, "E", "B"))

Mistakes and edge cases.

  • no seen set: in a graph with a cycle the search goes round and round and never ends
  • marking when taken out, not when added: a vertex can join the queue several times before it is taken out, which wastes work and can give it the wrong parent; mark it as soon as it is first seen
  • list.pop(0) as the queue: each pop shifts the whole list; use collections.deque and popleft()
  • a vertex you can't reach: it never gets a distance; decide what to return (-1, None, or leave it out)
  • the start is the goal: the distance is 0 and the path is just [start]

Quiz

  1. What does this print?

    from collections import deque
    
    def bfs_distances(graph, start):
        dist = {start: 0}
        queue = deque([start])
        while queue:
            v = queue.popleft()
            for w in graph[v]:
                if w not in dist:            # mark when first seen, not when taken out
                    dist[w] = dist[v] + 1
                    queue.append(w)
        return dist
    
    graph = {"A": ["B"], "B": ["A", "C", "D"], "C": ["B", "D"], "D": ["B", "C"]}
    print(sorted(bfs_distances(graph, "A").items()))
  2. Why does BFS mark a vertex as seen when it is added to the queue, not when it is taken out?

    • So it can't join the queue twice from two different neighbours
    • It makes no difference
    • To find the longest path
  3. A graph has 1,000 vertices and 5,000 edges. About how much work is one BFS?

    • About 11,000: each vertex once, each edge from both ends
    • About 1,000,000
    • About 10
  4. On a graph with a cycle, this never finishes. Which line should run only for a vertex that hasn't been seen yet?

    def reach(graph, start):
        queue = deque([start])
        order = []
        while queue:
            v = queue.popleft()
            order.append(v)
            for w in graph[v]:
                queue.append(w)
        return order
  5. The shortest path from E to B. What does this print?

    from collections import deque
    
    def shortest_path(graph, start, goal):
        parent = {start: None}
        queue = deque([start])
        while queue:
            v = queue.popleft()
            if v == goal:
                path = []
                while v is not None:         # walk back along the parents
                    path.append(v)
                    v = parent[v]
                return path[::-1]
            for w in graph[v]:
                if w not in parent:
                    parent[w] = v
                    queue.append(w)
        return []
    
    print(shortest_path({"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"], "D": ["B", "C", "F"], "E": ["C"], "F": ["D"]}, "E", "B"))

Coding tasks

  1. Write bfs_distances(graph, start): a dict from every vertex reachable from start to its distance (fewest edges), using a queue. graph is an adjacency-list dict.

  2. Write shortest_path(graph, start, goal): a path with the fewest edges from start to goal, as a list of vertices, found by BFS taking neighbours in the order they are listed. Return [] if goal can't be reached.

  3. Degrees of separation. Write separation(graph, a, b): the fewest friendship links from a to b (0 if they are the same person), or -1 if they are not connected at all.