AlgoTales · Roadmap

BFS

Intermediate · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Breadth-first search explores a network in rings: first everything one step away, then everything two steps away, and so on. It uses a waiting line (a queue) so nearer things are always handled before farther ones.

Practical use cases

  • Web app: People you may know. A social app wants to suggest friends. It starts at you, visits your friends (ring one), then their friends (ring two), and suggests the second-ring people you do not yet follow. Because it stops after two rings, it touches a few thousand profiles instead of the whole network of millions.
  • Web app: Threaded comment tree, level by level. A blog shows replies in layers: top comments first, then replies to them. Walking the comment tree ring by ring gives that exact order, and lets you add a "show 2 levels only" setting that simply stops after the second ring.
  • Web app: Site crawler for broken links. An SEO tool starts on your home page and checks every link, then every link on those pages. Doing it ring by ring finds pages nearest to the home page first, which are the ones visitors actually reach, and you can cap it at depth 3.
  • System: Flood fill and shortest hops. Paint-bucket tools fill a region by spreading outward from the click, and network tools find the fewest hops between machines the same way. Anything where "closest first" matters can use BFS. In every such tool the pattern is the same: a queue of places waiting their turn, and a note of which ones are already done, so nothing is visited twice.

The story: Gossip in the Mohalla

In a small neighbourhood, Mira heard a juicy bit of news: the school was closed tomorrow! She wanted everyone to know quickly. She did not shout across the street. She told her closest friends first.

Each friend then told their friends, who told their friends. Round by round, the news spread in rings: first the ones one hop away, then two hops, then three. Nobody was told twice, because people who already knew just nodded.

That ring-by-ring spreading is Breadth-First Search. And because it reaches the nearby people before the far ones, it discovers the fewest-hops path to anyone, which is how "people you may know" and map apps think.

How to spot this problem, and where you need it

You must explore a network starting from one place and need to handle the closest things first, or find out how many steps something is away, without wandering off deep into far corners.

Signs you need it

  • The wording includes "nearest", "fewest steps", "levels", "within 2 connections" or "degrees of separation".
  • Your recursive code goes deep down one branch first, but you actually wanted results grouped by distance from the start.
  • All steps cost the same, such as one click, one friendship, one hop, or one move on a grid.

Where to use it in a project

  • Friend or follower suggestions limited to friends of friends in a social feature.
  • Crawling or validating links from a home page to a fixed depth, or showing a category tree level by level.

The solution

Put the starting node in a queue and mark it as seen. Repeatedly take the front node out, look at its neighbours, and for each one not yet seen, mark it seen and add it to the back of the queue. Because the queue is first in, first out, all nodes at distance one are handled before distance two. Marking as seen prevents loops and repeat work. Record the distance as you add each node if you need it.

Payoff: Before: a deep search that drifts into unrelated profiles. After: friend suggestions found in two rings, a few thousand profiles checked instead of millions.

Explain it like I am 8

Drop a pebble in a pond. The ripples spread outward in circles: first the closest ring, then the next. BFS explores a network like those ripples. A waiting line (queue) makes sure you finish each ring before starting the next.

How it works, step by step

  1. Start somewhere. Put the start node in a queue and mark it as "visited".
  2. Take the front node. Look at all its neighbours.
  3. Add each unvisited neighbour to the back of the queue and mark it visited right away so nobody is queued twice.
  4. Repeat until the queue is empty. The order you took nodes out is the ring-by-ring order.

The code in four languages

PHP

<?php
// $graph: adjacency list, e.g. ['A' => ['B','C'], 'B' => ['A','D'], ...]
function bfs(array $graph, string $start): array {
    $visited = [$start => 0];          // node => hops from start
    $queue = new SplQueue();
    $queue->enqueue($start);

    while (!$queue->isEmpty()) {
        $node = $queue->dequeue();
        foreach ($graph[$node] as $next) {
            if (!isset($visited[$next])) {
                $visited[$next] = $visited[$node] + 1;   // one hop further
                $queue->enqueue($next);
            }
        }
    }
    return $visited;
}

$graph = ['A' => ['B', 'C'], 'B' => ['A', 'D', 'E'], 'C' => ['A', 'F'], 'D' => ['B'], 'E' => ['B', 'F'], 'F' => ['C', 'E']];
foreach (bfs($graph, 'A') as $node => $hops) echo $node, ': ', $hops, " hops\n";   // A: 0, B: 1, C: 1, D: 2, E: 2, F: 2

JavaScript

// graph: adjacency list, e.g. { A: ['B','C'], B: ['A','D'], ... }
function bfs(graph, start) {
  const visited = new Map([[start, 0]]);   // node -> hops from start
  const queue = [start];
  let head = 0;                            // index pointer = O(1) dequeue

  while (head < queue.length) {
    const node = queue[head++];
    for (const next of graph[node]) {
      if (!visited.has(next)) {
        visited.set(next, visited.get(node) + 1);   // one hop further
        queue.push(next);
      }
    }
  }
  return visited;
}

const graph = { A: ['B', 'C'], B: ['A', 'D', 'E'], C: ['A', 'F'], D: ['B'], E: ['B', 'F'], F: ['C', 'E'] };
for (const [node, hops] of bfs(graph, 'A')) console.log(node + ': ' + hops + ' hops');   // A: 0, B: 1, C: 1, D: 2, E: 2, F: 2

Java

import java.util.*;

public class Main {
    // graph: adjacency list, e.g. {A=[B, C], B=[A, D], ...}. Returns node -> hops from start.
    static Map<String, Integer> bfs(Map<String, List<String>> graph, String start) {
        Map<String, Integer> visited = new LinkedHashMap<>();   // node -> hops from start
        visited.put(start, 0);
        Queue<String> queue = new ArrayDeque<>();
        queue.add(start);

        while (!queue.isEmpty()) {
            String node = queue.remove();
            for (String next : graph.get(node)) {
                if (!visited.containsKey(next)) {
                    visited.put(next, visited.get(node) + 1);   // one hop further
                    queue.add(next);
                }
            }
        }
        return visited;
    }

    public static void main(String[] args) {
        Map<String, List<String>> graph = Map.of(
            "A", List.of("B", "C"), "B", List.of("A", "D", "E"), "C", List.of("A", "F"),
            "D", List.of("B"), "E", List.of("B", "F"), "F", List.of("C", "E"));
        for (var entry : bfs(graph, "A").entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue() + " hops");
        }
    }
}

Go

package main

import (
	"fmt"
	"sort"
)

// bfs returns node -> hops from start. graph is an adjacency list.
func bfs(graph map[string][]string, start string) map[string]int {
	visited := map[string]int{start: 0} // node -> hops from start
	queue := []string{start}
	head := 0 // index pointer = O(1) dequeue

	for head < len(queue) {
		node := queue[head]
		head++
		for _, next := range graph[node] {
			if _, seen := visited[next]; !seen {
				visited[next] = visited[node] + 1 // one hop further
				queue = append(queue, next)
			}
		}
	}
	return visited
}

func main() {
	graph := map[string][]string{
		"A": {"B", "C"}, "B": {"A", "D", "E"}, "C": {"A", "F"},
		"D": {"B"}, "E": {"B", "F"}, "F": {"C", "E"},
	}
	hops := bfs(graph, "A")
	names := make([]string, 0, len(hops))
	for v := range hops {
		names = append(names, v)
	}
	sort.Strings(names)
	for _, v := range names {
		fmt.Printf("%s: %d hops\n", v, hops[v])
	}
}

Time: O(V + E) · Extra space: O(V). V = nodes, E = connections. Every node and every connection is looked at about once.

Watch out for

  • Marking nodes visited when you take them out instead of when you add them. The same node can sit in the queue many times.
  • Using a stack instead of a queue. That makes it depth-first search, which explores differently.

Quick check

  1. Which structure does BFS use to remember what to visit next?
    • Stack
    • Queue
    • Tree
  2. BFS is great for finding…
    • The path with the fewest hops
    • The cheapest path with weights
    • The longest path
  3. Why mark a node visited as soon as it is queued?
    • To avoid queuing it twice
    • To save memory
    • No reason