Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 68 / 101

Explore the network.

Use adjacency lists and a queue to explore a network without revisiting nodes forever.

ADVANCED LAB
BY NAVAN SAMI◷ 12 MIN READPYTHON 3

01 The idea

A graph represents vertices and edges. An adjacency list maps each vertex to its neighbours. Breadth-first search explores by distance from a starting vertex using a queue, making it suitable for shortest paths when every edge has equal cost. Record vertices as discovered when enqueuing them to avoid inserting the same vertex repeatedly.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

graphs_bfs.py
from collections import deque

def shortest_path(graph, start, goal):
    queue = deque([start])
    parent = {start: None}
    while queue:
        node = queue.popleft()
        if node == goal:
            path = []
            while node is not None:
                path.append(node); node = parent[node]
            return list(reversed(path))
        for neighbour in graph.get(node, []):
            if neighbour not in parent:
                parent[neighbour] = node
                queue.append(neighbour)
    return None
network = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(shortest_path(network, "A", "D"))
↳ EXPECTED OUTPUT
['A', 'B', 'D']

03 Under the hood

  1. 1

    The parent dictionary doubles as the discovered set and the information needed to reconstruct a path.

  2. 2

    Queue order ensures all distance-one candidates are explored before distance-two candidates. When multiple shortest paths exist, neighbour order affects which one is returned.

  3. 3

    With adjacency lists, traversal takes O(V + E) work over reachable vertices and edges. Weighted shortest paths need a different algorithm, such as Dijkstra’s for nonnegative weights.

04 Your turn, builder

A SMALL MISSION

Check that a disconnected destination returns None and that a start equal to the goal yields a one-vertex path.

Reveal one possible solution +
one_possible_solution.py
from collections import deque
def reachable(graph, start, goal):
    queue, seen = deque([start]), {start}
    while queue:
        node = queue.popleft()
        if node == goal: return True
        for neighbour in graph.get(node, []):
            if neighbour not in seen:
                seen.add(neighbour); queue.append(neighbour)
    return False
print(reachable({"A": []}, "A", "Z"))
print(reachable({"A": []}, "A", "A"))

05 Check your signal

QUICK SIGNAL CHECK

When does BFS find a shortest path?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.