BFS algorithm Python level
Run a BFS algorithm Python level and compare its fewest-step route with DFS, Dijkstra, and A star.
Published here , updated · 3 sources · Resume reading
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]:
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)python3 bfs_grid.pyCaptured output:
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]:
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)python3 bfs_dungeon.pyCaptured output:
steps 12 cost 32The 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
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
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)
PYCaptured output:
BFS steps 12 cost 32
Dijkstra steps 14 cost 14Same 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
python3 bfs.pyREADME lists the command and places BFS beside DFS, Dijkstra, and A star [1]. DFS explores deeply. Dijkstra minimizes summed edge cost [3]. A star 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 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.

Keep this guide
Filed under Dev explainers
Questions about this guide
How do I run this BFS algorithm Python level?
Run python3 bfs.py from the repository folder.
What does this BFS algorithm optimize on the map?
BFS finds the fewest steps, not the lowest mud cost.
Sources
- ALGO ARCADE READMEgithub.com
- ALGO ARCADE BFS sourcegithub.com
- ALGO ARCADE Dijkstra sourcegithub.com