# BFS algorithm Python level

> Run a BFS algorithm Python level and compare its fewest-step route with DFS, Dijkstra, and A star.

Source: https://fullbytedeveloper.com/blog/bfs-algorithm-python
Keyword: BFS
Published here: 2026-11-24, updated 2026-12-03

Breadth-first search finds the fewest steps between S and T on an unweighted grid by dequeuing cells in discovery order [2]. ALGO ARCADE level 8 shares the mud dungeon with Dijkstra [1]. A captured run finds twelve steps with mud cost thirty-two for BFS, while Dijkstra takes fourteen steps for cost fourteen [2][3].

## Small grid you can run in one file

This board shows why queue order matters before mud weights enter [2]:

```python title="bfs_grid.py"
from collections import deque

grid = [list("S..#"), list(".#.."), list("..#G")]
start = (0, 0)
goal = (2, 3)
q = deque([start])
came_from = {start: None}
while q:
    room = q.popleft()
    if room == goal:
        break
    r, c = room
    for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#":
            nxt = (nr, nc)
            if nxt not in came_from:
                came_from[nxt] = room
                q.append(nxt)
path = []
cur = goal
while cur is not None:
    path.append(cur)
    cur = came_from[cur]
path.reverse()
print("steps", len(path) - 1, "path", path)
```

```bash
python3 bfs_grid.py
```

Captured output:

```text
steps 5 path [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
```

Five steps is optimal for hop count when every open tile costs one edge [2]. Trace it: from `S` the queue grows through distance-1 cells, then distance-2, and so on. The first time `G` leaves the front of the deque, no shorter hop path exists, because every shorter path would have been dequeued earlier.

## ALGO ARCADE DUNGEON path

This script mirrors bfs.py on the shared DUNGEON map [2]:

```python title="bfs_dungeon.py"
from collections import deque

DUNGEON = [
    ".............",
    ".###########.",
    ".#.........#.",
    "S...~~~~~...T",
    ".#.........#.",
    ".###########.",
    ".............",
    ".............",
]

def find(grid, ch):
    for y, row in enumerate(grid):
        for x, cell in enumerate(row):
            if cell == ch:
                return (y, x)
    raise ValueError(ch)

def neighbours(grid, pos):
    y, x = pos
    for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
        ny, nx = y + dy, x + dx
        if 0 <= ny < len(grid) and 0 <= nx < len(grid[0]) and grid[ny][nx] != "#":
            yield (ny, nx)

def step_cost(grid, pos):
    return 5 if grid[pos[0]][pos[1]] == "~" else 1

def bfs(grid):
    start, goal = find(grid, "S"), find(grid, "T")
    came_from = {start: None}
    q = deque([start])
    while q:
        room = q.popleft()
        if room == goal:
            break
        for nxt in neighbours(grid, room):
            if nxt not in came_from:
                came_from[nxt] = room
                q.append(nxt)
    path = []
    cur = goal
    while cur is not None:
        path.append(cur)
        cur = came_from[cur]
    path.reverse()
    return path

path = bfs(DUNGEON)
cost = sum(step_cost(DUNGEON, p) for p in path[1:])
print("steps", len(path) - 1, "cost", cost)
```

```bash
python3 bfs_dungeon.py
```

Captured output:

```text
steps 12 cost 32
```

The docstring warns that BFS counts steps, not effort, and that mud costs five per tile while floor costs one [2]. Twelve hops through the mud strip beats a longer floor walk on hop count, so the algorithm takes the expensive mud. That is correct for BFS and wrong if your interviewer meant cheapest cost.

## Queue versus stack

<figure>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 260" role="img" aria-label="BFS clears hop rings from S before deeper cells reach T">
  <defs>
    <marker id="arrowBfsPython" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">
      <path d="M0,0 L8,3 L0,6 Z" fill="#14b8a6"/>
    </marker>
  </defs>
  <rect x="0" y="0" width="720" height="260" rx="12" fill="#0b1f3a"/>
  <text x="24" y="36" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="16" font-weight="700">deque front to back</text>
  <rect x="24" y="56" width="64" height="64" rx="8" fill="#123052" stroke="#f59e0b" stroke-width="2"/>
  <text x="44" y="96" fill="#f8fafc" font-family="ui-monospace, monospace" font-size="16">S</text>
  <path d="M88 88 H136" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowBfsPython)"/>
  <rect x="144" y="56" width="88" height="64" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="160" y="96" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">ring 1</text>
  <path d="M232 88 H280" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowBfsPython)"/>
  <rect x="288" y="56" width="88" height="64" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="304" y="96" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">ring 2</text>
  <path d="M376 88 H424" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowBfsPython)"/>
  <rect x="432" y="56" width="88" height="64" rx="8" fill="#123052" stroke="#64748b" stroke-width="2"/>
  <text x="448" y="96" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">mud ~</text>
  <path d="M520 88 H568" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowBfsPython)"/>
  <rect x="576" y="56" width="64" height="64" rx="8" fill="#123052" stroke="#f59e0b" stroke-width="2"/>
  <text x="594" y="96" fill="#f8fafc" font-family="ui-monospace, monospace" font-size="16">T</text>
  <rect x="24" y="148" width="330" height="88" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="40" y="180" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">BFS: popleft, appendright</text>
  <text x="40" y="208" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">all distance-d cells before d+1</text>
  <rect x="374" y="148" width="322" height="88" rx="8" fill="#123052" stroke="#64748b" stroke-width="2"/>
  <text x="390" y="180" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">DFS: stack LIFO</text>
  <text x="390" y="208" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">no fewest-step guarantee</text>
</svg>
</figure>

*BFS finishes every cell at hop distance d before any at d+1; a stack depth-first search can reach T without that guarantee.*

That layer invariant is why BFS returns the shortest hop count on unweighted graphs [2]. DFS can stumble into `T` after a long corridor dig, or after a short one, depending on neighbor order. Reaching the goal with a stack proves connectivity, not hop optimality. Interviews that say "shortest path" on an unweighted maze almost always want the deque version.

## Compare Dijkstra on the same map

```bash
git clone https://github.com/kamilikamil/algo-arcade.git
cd algo-arcade
python3 - <<'PY'
from bfs import bfs, DUNGEON
from dijkstra import dijkstra
from arcade import step_cost

def tally(path):
    return len(path) - 1, sum(step_cost(DUNGEON, p) for p in path[1:])

for name, fn in (("BFS", bfs), ("Dijkstra", dijkstra)):
    path = fn(DUNGEON)
    steps, cost = tally(path)
    print(name, "steps", steps, "cost", cost)
PY
```

Captured output:

```text
BFS steps 12 cost 32
Dijkstra steps 14 cost 14
```

Same dungeon, different objective [1]. When interviews say shortest path without weights, they mean BFS. When edges have positive cost, switch to Dijkstra [3]. Memorize the pair of numbers above: twelve hops for 32, fourteen hops for 14. If your own port returns those two pairs, the neighbor function and cost function are wired correctly.

## Why first discovery wins

Mark a cell when you enqueue it into `came_from`, not when you dequeue it. The first time BFS sees a cell, that discovery arrived on a shortest hop path from `S` [2]. Later arrivals cannot be shorter in hop count on an unweighted graph, so you skip them. If you wait until dequeue to mark visited, the same cell can sit in the queue many times and memory grows for no gain.

Parent pointers in `came_from` are the path. When `T` dequeues, walk parents back to `S` and reverse. Students who only print that `T` was reached have proved reachability. The assignment usually wants the actual corridor, which is the reverse walk.

## Level commands and neighbors in the series

```bash
python3 bfs.py
```

README lists the command and places BFS beside DFS, Dijkstra, and A star [1]. [DFS](/blog/dfs-algorithm-python) explores deeply. [Dijkstra](/blog/dijkstra-algorithm-python) minimizes summed edge cost [3]. [A star](/blog/a-star-algorithm-python) adds a goal heuristic on top of Dijkstra [3].

Calling BFS on weighted mud and expecting cheapest cost is the usual mistake. The algorithm does what the docstring says: fewest steps, not least effort [2].

## Implementation mistakes to avoid

Using a Python list as a queue with `pop(0)`. That is `O(n)` per pop. Use `collections.deque` instead [2].

Rebuilding a path without parent pointers after you reach `T`. You will invent a route that the search never recorded.

Adding diagonal moves without stating the model. Four-neighbor and eight-neighbor BFS differ in both length and wall clipping.

Forgetting that walls block expansion. Copy `neighbours` from the level or paths leak through bricks [2].

Treating DFS as a drop-in "search" for maze shortest path. Swap the deque for a stack and the hop guarantee disappears on the same grid.

## Complexity the level prints

Metadata cites O(V + E) time and O(V) memory for queue plus came_from [2]. Each room is discovered once, which is why BFS stays the teaching default before weights [1]. On a grid, `V` is open cells and `E` is roughly four times that, minus walls. The mud dungeon is small enough that constant factors dominate wall time; the counters still teach the asymptotic shape you will need on larger graphs.

## Reconstruct paths and teach with layers

After the goal dequeues, walk came_from from T back to S and reverse the list. Students who only print the goal coordinate have not finished the assignment [2].

Optional homework: store depth when you enqueue and print layer by layer. The arcade level skips that printout, but it matches what you see running `python3 bfs.py` [1][2]. A depth map also makes the mud mistake visible: the depth-12 path can cross several `~` tiles while a depth-14 floor path stays cheap.

Multi-source BFS seeds the queue with several starters. Fire spread and word-ladder puzzles use that shape. Seed every fire cell (or every dictionary word of length one edit from the start) at depth zero, then expand once. The repo stays single-source so the queue invariant stays visible [2], but the same `popleft` / `append` loop works after you push multiple starts.

0-1 BFS is the next step when some edges cost 0 and others cost 1: use `appendleft` for zero-cost edges and `append` for unit edges. That is not the arcade level. Mention it only so you do not paste plain BFS into a graph that already has two edge weights.

## What to study next

Open [Dev explainers](https://fullbytedeveloper.com/blog/topic/dev-explainers) and walk the README order through sorting, search, then graphs [1]. Run the dungeon compare script once, then change one mud tile to floor and re-run: hop count for BFS may stay twelve while Dijkstra's cost drops, which is a clean way to feel the objective gap without reading more theory.

A list used as a queue with `pop(0)` shifts every remaining item and turns a simple grid walk into something closer to quadratic work. The `collections.deque` left-pop stays cheap. On a teaching maze the difference is invisible; on a large grid it shows up in wall time before you notice the bug in the visit set.

Send this to the friend who keeps using DFS on unweighted mazes and calls it shortest path.

Image: A grid of cells with a teal wavefront expanding in concentric rings from a start cell toward a target crystal, beside a thinner amber cheapest-cost path that takes a different, longer step count across the same mud-tinted cells, with no typography or numerals.
https://fullbytedeveloper.com/media/bfs-algorithm-python/bfs-algorithm-python-venice.webp
A queue finds the fewest steps. A cost-aware path on the same map can choose a cheaper route.

## Sources

1. [ALGO ARCADE README](https://github.com/kamilikamil/algo-arcade/blob/main/README.md)
2. [ALGO ARCADE BFS source](https://github.com/kamilikamil/algo-arcade/blob/main/bfs.py)
3. [ALGO ARCADE Dijkstra source](https://github.com/kamilikamil/algo-arcade/blob/main/dijkstra.py)
