Explore Library
Code QuizAdvanced

BFS Frontier Order

Spot why this breadth-first search does not explore nodes in level order.

Codejavascript
function bfs(graph, start, goal) {
  const frontier = [start];
  const visited = new Set([start]);
  while (frontier.length > 0) {
    const node = frontier.pop();
    if (node === goal) return true;
    for (const next of graph[node]) {
      if (!visited.has(next)) {
        visited.add(next);
        frontier.push(next);
      }
    }
  }
  return false;
}

This is meant to be breadth-first search, but it behaves like depth-first. What is the bug?

Watch the code walkthrough

Watch on YouTube →