Skip to content
Ayotl

← Algorithms · Lesson 7/11

The maze: breadth-first search (BFS)

▶ Watch it as a video: one minute with LeIA

Watch on YouTube →

✕
1/8

A maze is a graph

A maze of cells is written as rows of text: # is a wall and . is a corridor. Each open cell is a vertex, and its neighbors are the open cells above, below, left and right. Nothing else to build: neighbors are computed on the fly.

We name each cell by its row and column, as text: "4,0" is the entrance (row 4, column 0) and "4,10" the exit. That way they work as keys in an object. The computer doesn't see the drawing: all it can ask is "who are this cell's neighbors?".

  • x wall
  • h entrance
  • f exit
leccion.js

$ node leccion.js

Press RUN (or Ctrl+Enter).

What to look at

  • The entrance has just one neighbor: the cell to its right. To its left is the edge, and lab[4][-1] is undefined, not ".".
  • "4,1" has three: up (the snake), down (the corridor) and the entrance, where we came from.
  • ?. avoids an error when asking for a row that doesn't exist, like −1.
The whole lesson on one page

A maze is a graph

A maze of cells is written as rows of text: # is a wall and . is a corridor. Each open cell is a vertex, and its neighbors are the open cells above, below, left and right. Nothing else to build: neighbors are computed on the fly.

We name each cell by its row and column, as text: "4,0" is the entrance (row 4, column 0) and "4,10" the exit. That way they work as keys in an object. The computer doesn't see the drawing: all it can ask is "who are this cell's neighbors?".

  • x wall
  • h entrance
  • f exit
const lab = [
  "###########",
  "#...#...#.#",
  "#.#.#.#.#.#",
  "#.#...#...#",
  "..#######..",
  "#.........#",
  "#.#.###.#.#",
  "#.#...#.#.#",
  "###########",
];

// the open cells next to c ("row,column"),
// in this order: up, right, down, left
function vecinos(c) {
  const [y, x] = c.split(",").map(Number);
  return [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]]
    .filter(([f, k]) => lab[f]?.[k] === ".")
    .map(([f, k]) => f + "," + k);
}

console.log(vecinos("4,0"));   // the entrance
console.log(vecinos("4,1"));   // it splits in two here
console.log(vecinos("5,5"));   // halfway along the bottom corridor
  • The entrance has just one neighbor: the cell to its right. To its left is the edge, and lab[4][-1] is undefined, not ".".
  • "4,1" has three: up (the snake), down (the corridor) and the entrance, where we came from.
  • ?. avoids an error when asking for a row that doesn't exist, like −1.

BFS: layer by layer, with a queue

Breadth-first search (BFS) puts the entrance in a queue. Then, while anyone's left, it takes the one at the front and adds its new neighbors at the back. In de ("from") it notes which cell each one came from: that tells who already went in (v in de) and, at the end, rebuilds the path.

The queue is the one from the queues lesson: an array with a cabeza (head) index that only moves forward, no shift, so taking one out is O(1). When the exit comes out, it's done (break). The path is built backwards: from the exit, de says where it came from, and where that one came from, back to the entrance.

  • x wall
  • h entrance
  • f exit
  • b the path BFS finds
const lab = [
  "###########",
  "#...#...#.#",
  "#.#.#.#.#.#",
  "#.#...#...#",
  "..#######..",
  "#.........#",
  "#.#.###.#.#",
  "#.#...#.#.#",
  "###########",
];

// the open cells next to c ("row,column"),
// in this order: up, right, down, left
function vecinos(c) {
  const [y, x] = c.split(",").map(Number);
  return [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]]
    .filter(([f, k]) => lab[f]?.[k] === ".")
    .map(([f, k]) => f + "," + k);
}

function bfs(ini, fin) {
  const de = { [ini]: ini };
  const cola = [ini]; let cabeza = 0;
  while (cabeza < cola.length) {
    const c = cola[cabeza++];
    if (c === fin) break;
    for (const v of vecinos(c)) {
      if (v in de) continue;
      de[v] = c; cola.push(v);
    }
  }
  const camino = [fin];
  while (camino[0] !== ini)
    camino.unshift(de[camino[0]]);
  return camino;
}

const camino = bfs("4,0", "4,10");
console.log(camino.length - 1, "steps");
console.log(camino.join(" → "));
  • 12 steps: down to the corridor, all the way across and up to the exit.
  • camino has 13 cells: the steps are one fewer, because the entrance doesn't count.
  • de[ini] = ini marks the entrance as seen from the start, so nobody adds it again.

Layer by layer

If instead of "where it came from" you note the distance (the discoverer's plus one), you see the layers: the entrance is 0, its neighbor 1, the two at the fork 2, and so on. The wave moves evenly through the snake and the corridor.

Look at the queue's order: the distances never go down (0 1 2 2 3 3 …). That's because the queue serves in order of arrival: everyone in layer d comes out before anyone in d + 1, who arrived later. That's the whole magic of BFS.

const lab = [
  "###########",
  "#...#...#.#",
  "#.#.#.#.#.#",
  "#.#...#...#",
  "..#######..",
  "#.........#",
  "#.#.###.#.#",
  "#.#...#.#.#",
  "###########",
];

// the open cells next to c ("row,column"),
// in this order: up, right, down, left
function vecinos(c) {
  const [y, x] = c.split(",").map(Number);
  return [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]]
    .filter(([f, k]) => lab[f]?.[k] === ".")
    .map(([f, k]) => f + "," + k);
}

function capas(ini) {
  const dist = { [ini]: 0 };
  const cola = [ini]; let cabeza = 0;
  while (cabeza < cola.length) {
    const c = cola[cabeza++];
    for (const v of vecinos(c)) {
      if (v in dist) continue;
      dist[v] = dist[c] + 1; cola.push(v);
    }
  }
  return { dist, cola };
}

const { dist, cola } = capas("4,0");
for (let y = 0; y < lab.length; y++) {
  let fila = "";
  for (let x = 0; x < lab[y].length; x++) {
    const d = dist[y + "," + x];
    fila += d === undefined ? " ##" : String(d).padStart(3);
  }
  console.log(fila);
}
console.log("the queue, as distances:", cola.map((c) => dist[c]).join(" "));
  • No break here: it walks the whole maze. The exit is 12 away; the farthest cell, 15.
  • Through the snake, the exit would be 20 away. Its tip next to the exit (3,9) has 12, not 18: the wave from the corridor got there first.
  • The queue comes out sorted without sorting anything: 0, 1, 2, 2, 3, 3, …

Why it's the shortest (and DFS isn't)

BFS checks all cells at distance 1 before any at distance 2, all at 2 before those at 3… So the first time it touches the exit, there can't be a shorter path: it would have found it in an earlier layer. That's why BFS gives the path with the fewest steps (in a maze where every step costs the same).

Depth-first search (DFS) uses a stack, or recursion: it dives down the first corridor to the end and only backs up when stuck. It finds a path, not necessarily the shortest: with this neighbor order (up first) it goes into the snake and takes 20. Both cost O(V + E): each cell goes in once and each neighbor is looked at once.

  • x wall
  • h entrance
  • f exit
  • m the path DFS finds
const lab = [
  "###########",
  "#...#...#.#",
  "#.#.#.#.#.#",
  "#.#...#...#",
  "..#######..",
  "#.........#",
  "#.#.###.#.#",
  "#.#...#.#.#",
  "###########",
];

// the open cells next to c ("row,column"),
// in this order: up, right, down, left
function vecinos(c) {
  const [y, x] = c.split(",").map(Number);
  return [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]]
    .filter(([f, k]) => lab[f]?.[k] === ".")
    .map(([f, k]) => f + "," + k);
}

function bfs(ini, fin) {
  const de = { [ini]: ini };
  const cola = [ini]; let cabeza = 0;
  while (cabeza < cola.length) {
    const c = cola[cabeza++];
    if (c === fin) break;
    for (const v of vecinos(c)) {
      if (v in de) continue;
      de[v] = c; cola.push(v);
    }
  }
  const camino = [fin];
  while (camino[0] !== ini)
    camino.unshift(de[camino[0]]);
  return camino;
}

// depth-first: dives down the first neighbor to the end
function dfs(c, fin, visto = new Set([c])) {
  if (c === fin) return [c];
  for (const v of vecinos(c)) {
    if (visto.has(v)) continue;
    visto.add(v);
    const resto = dfs(v, fin, visto);
    if (resto) return [c, ...resto];
  }
  return null;   // no way through here
}

console.log("BFS:", bfs("4,0", "4,10").length - 1, "steps");
console.log("DFS:", dfs("4,0", "4,10").length - 1, "steps");
  • BFS: 12. DFS: 20, through the snake at the top.
  • Change the order in vecinos so it looks down before up: DFS will take the corridor and give 12. It got lucky; BFS doesn't depend on luck.

Practice with a video challenge

Further reading