Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Graphs and connections
EXPERIMENT 37 / 66

Explore the network.

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

BY NAVAN SAMI◷ 10 MIN READCOREALGORITHM

01 Model 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.

THE THING THAT MUST STAY TRUE

A vertex is discovered once, and the queue explores increasing edge distance.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
ENQUEUE the start and mark it discovered
DEQUEUE the next vertex
DISCOVER and enqueue unseen neighbours
RECONSTRUCT the route through parent links
ALGORITHM STUDIOLIVE IN YOUR BROWSER
ABCDEF
VISITED 0/6QUEUE ASTEP 1/8

Discover A and put it in the queue.

Current operation Ordered / visitedPredict. Step. Explain.

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

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']
  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 Count the cost

TIME

O(V + E) on adjacency lists

SPACE

O(V) traversal state

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

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"))

06 Check your reasoning

QUICK SIGNAL CHECK

When does BFS find a shortest path?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.