cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 63 of 218
Ideas this builds on
Graphs63 / 218

BFS spreads in distance layers

Picture

Imagine a ripple spreading from a starting point. First it reaches everything one move away, then two moves away, then three. BFS maintains that ordering with a queue. When each edge has the same positive cost, fewer edges also means lower total cost.

Predict

When should you mark a vertex discovered: when you add it to the queue, or only when you remove it?

Reveal the reasoning

Mark it when adding it. Otherwise several parents can queue the same vertex before its first removal. First discovery already gives the shortest edge-count distance under BFS’s layer ordering.

Go deeper: the frontier carries a guarantee
from collections import deque

def distances(graph, start):
    distance = {start: 0}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in graph.get(node, []):
            if neighbor not in distance:
                distance[neighbor] = distance[node] + 1
                queue.append(neighbor)
    return distance

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
assert distances(graph, "A") == {"A": 0, "B": 1, "C": 1, "D": 2}

After processing A, the queue holds B, C, both at distance 1. Processing B appends D at distance 2 behind the remaining distance-1 work. No longer route can discover D before every possible shorter predecessor has had its turn.

With adjacency lists, BFS takes O(V+E) time over the reachable portion and O(V) extra space in the worst case. Use deque.popleft(); removing index zero from a Python list shifts elements.

To reconstruct one shortest path, store a parent on first discovery and follow parents backward from the destination. To count shortest paths, also accumulate counts from other parents at the preceding distance. “Already discovered” does not mean every question should ignore every later edge.

Analogy limit: a real ripple over unequal terrain is not this algorithm. BFS minimizes edge count; arbitrary edge weights require another argument.

Change one rule

There is a direct edge of cost 20 to the exit, and a two-edge route costing 1 per edge. Which route will edge-count BFS prefer?

Check the variation

The direct one-edge route, even though its cost is worse. For nonnegative varying weights, use a cost-aware method such as Dijkstra.

Connect

DFS chooses a different frontier order. Grid DP counts continuations under acyclic movement. Dijkstra orders the frontier by tentative total cost.