AlgoTales · Roadmap

BFS shortest path

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

Where you will meet this in real life

When every step costs the same, BFS finds the route with the fewest steps, and by remembering where you came from at each place you can rebuild the actual route. It is the first tool for "shortest way" questions on equal-cost links.

Practical use cases

  • Web app: Fewest metro changes in a transit app. A journey planner shows the route with the fewest stops between two stations. The search spreads outward one stop at a time and the first time it touches the destination, that is the shortest in stops. Following the saved "came from" notes backwards prints the station list.
  • Web app: Degrees of separation badge. A professional network shows "2nd connection" beside a profile. The app runs a BFS from you and reports how many rings away that person is, stopping at 3 so it never explores the whole site. The same saved notes let the app draw the exact path as a highlighted line, so users see the whole route, not just the number.
  • Web app: Solving a puzzle or word ladder game. A browser game asks you to change one letter at a time to turn COLD into WARM. Each word is a node, one-letter changes are links, and BFS gives the shortest chain, which the game uses for hints. Hints in the game simply re-run the search from the current word, so help is always the shortest remaining way.
  • System: Grid games and network hops. A character on a grid map finds the fewest moves around walls, and network tools count the fewest routers between two machines. The common thread is that every move costs the same, so the first time the ring touches the goal is guaranteed to be the closest.

The story: The Fewest Stops to the Match

Mira and Kabir were going to a cricket match across the city. The metro map looked like spaghetti. "Which way has the fewest stops?" asked Kabir. Mira recalled the gossip ripples, BFS, and tried something with them.

She started at home and wrote "0 stops" on it. All stations one stop away got "1". Then the stations reached from those got "2", and so on, ring by ring. When the ripple first touched the cricket ground, its number was the answer. No other route could be shorter, because shorter routes would have been reached in an earlier ring.

But Kabir had a good point: "A number is nice, but how do I go there?" So Mira added a small habit. Whenever she discovered a station, she wrote down who told her about it: its parent. At the end she followed those notes backwards from the ground to home, then flipped the list.

That is the BFS shortest path: BFS plus a parent for each vertex. It is the shortest path whenever every edge counts the same.

How to spot this problem, and where you need it

You need the shortest way between two points, measured in number of steps, and every step or link is considered the same cost.

Signs you need it

  • The problem says "minimum number of moves", "fewest stops", "shortest chain" or "minimum hops", with no prices or distances on the links.
  • A plain DFS finds a route, but it is long and winding, not the shortest.
  • The world is a grid or a map where each move to a neighbour counts as one.

Where to use it in a project

  • A route finder for a metro, bus or railway app where changes and stops are counted equally.
  • A "how are we connected" feature showing the shortest chain of friends or colleagues.

The solution

Start BFS from the source and store, for every node you add to the queue, which node you came from. Stop when you take the destination off the queue. Then start at the destination and follow the "came from" notes back to the source, and reverse that list. Because BFS handles nodes in order of distance, the first arrival at the destination is guaranteed to be the shortest.

Payoff: Before: a DFS route of 14 stops. After: the best route of 6 stops, with the full station list, found in one pass.

Explain it like I am 8

Drop a pebble in a pond and watch the rings. The first ring to touch the toy boat tells you how far it is. To remember the way, every time a ring touches a new spot, write down which spot it came from. Follow those notes backwards to get the route.

How it works, step by step

  1. Start BFS at the source. Set its distance to 0 and put it in the queue.
  2. Take the front vertex. For each unvisited neighbour set dist = dist[current] + 1 and parent = current, then queue it.
  3. Stop early when the target is discovered (or run to the end to get all distances).
  4. Rebuild the route: start from the target and keep jumping to parent until you reach the source.
  5. Reverse the list to read the path from source to target.

The code in four languages

PHP

<?php
// Returns the fewest-hops path from $src to $dst, or [] if there is none.
function shortestPath(array $graph, string $src, string $dst): array {
    $parent = [$src => null];            // also works as the "visited" set
    $queue = new SplQueue();
    $queue->enqueue($src);
    while (!$queue->isEmpty()) {
        $u = $queue->dequeue();
        if ($u === $dst) break;           // reached the target: done
        foreach ($graph[$u] as $v) {
            if (!array_key_exists($v, $parent)) {
                $parent[$v] = $u;         // remember who told us about $v
                $queue->enqueue($v);
            }
        }
    }
    if (!array_key_exists($dst, $parent)) return [];
    $path = [];
    for ($n = $dst; $n !== null; $n = $parent[$n]) $path[] = $n;   // walk back
    return array_reverse($path);
}

$graph = [
    'S' => ['A', 'B'], 'A' => ['S', 'C'], 'B' => ['S', 'D'],
    'C' => ['A', 'T'], 'D' => ['B', 'T'], 'T' => ['C', 'D'],
];
$path = shortestPath($graph, 'S', 'T');
echo implode(' -> ', $path) . ' (' . (count($path) - 1) . ' hops)';

JavaScript

// Returns the fewest-hops path from src to dst, or [] if there is none.
function shortestPath(graph, src, dst) {
  const parent = new Map([[src, null]]);   // also works as the "visited" set
  const queue = [src];
  let head = 0;
  while (head < queue.length) {
    const u = queue[head++];
    if (u === dst) break;                  // reached the target: done
    for (const v of graph[u]) {
      if (!parent.has(v)) {
        parent.set(v, u);                  // remember who told us about v
        queue.push(v);
      }
    }
  }
  if (!parent.has(dst)) return [];
  const path = [];
  for (let n = dst; n !== null; n = parent.get(n)) path.push(n);   // walk back
  return path.reverse();
}

const graph = {
  S: ['A', 'B'], A: ['S', 'C'], B: ['S', 'D'],
  C: ['A', 'T'], D: ['B', 'T'], T: ['C', 'D'],
};
const path = shortestPath(graph, 'S', 'T');
console.log(path.join(' -> ') + ' (' + (path.length - 1) + ' hops)');

Java

import java.util.*;

public class Main {
    // Returns the fewest-hops path from src to dst, or an empty list if there is none.
    static List<String> shortestPath(Map<String, List<String>> graph, String src, String dst) {
        Map<String, String> parent = new HashMap<>();   // also works as the "visited" set
        parent.put(src, null);
        Queue<String> queue = new ArrayDeque<>();
        queue.add(src);
        while (!queue.isEmpty()) {
            String u = queue.remove();
            if (u.equals(dst)) break;                   // reached the target: done
            for (String v : graph.get(u)) {
                if (!parent.containsKey(v)) {
                    parent.put(v, u);                   // remember who told us about v
                    queue.add(v);
                }
            }
        }
        if (!parent.containsKey(dst)) return List.of();
        List<String> path = new ArrayList<>();
        for (String n = dst; n != null; n = parent.get(n)) path.add(n);   // walk back
        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args) {
        Map<String, List<String>> graph = Map.of(
            "S", List.of("A", "B"), "A", List.of("S", "C"), "B", List.of("S", "D"),
            "C", List.of("A", "T"), "D", List.of("B", "T"), "T", List.of("C", "D"));
        List<String> path = shortestPath(graph, "S", "T");
        System.out.println(String.join(" -> ", path) + " (" + (path.size() - 1) + " hops)");
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// shortestPath returns the fewest-hops path from src to dst, or nil if there is none.
func shortestPath(graph map[string][]string, src, dst string) []string {
	parent := map[string]string{src: ""} // also works as the "visited" set ("" = no parent)
	queue := []string{src}
	for head := 0; head < len(queue); head++ {
		u := queue[head]
		if u == dst {
			break // reached the target: done
		}
		for _, v := range graph[u] {
			if _, seen := parent[v]; !seen {
				parent[v] = u // remember who told us about v
				queue = append(queue, v)
			}
		}
	}
	if _, found := parent[dst]; !found {
		return nil
	}
	var path []string
	for n := dst; n != ""; n = parent[n] { // walk back
		path = append(path, n)
	}
	for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
		path[i], path[j] = path[j], path[i] // reverse
	}
	return path
}

func main() {
	graph := map[string][]string{
		"S": {"A", "B"}, "A": {"S", "C"}, "B": {"S", "D"},
		"C": {"A", "T"}, "D": {"B", "T"}, "T": {"C", "D"},
	}
	path := shortestPath(graph, "S", "T")
	fmt.Printf("%s (%d hops)\n", strings.Join(path, " -> "), len(path)-1)
}

Time: O(V + E) · Extra space: O(V). Same cost as plain BFS. The parent notes add only one value per vertex.

Watch out for

  • Using BFS when the edges have different weights. It counts hops, not cost. Use Dijkstra then.
  • Forgetting to store the parent, so you know the distance but not the route.
  • Forgetting to reverse the path after walking back from the target.

Quick check

  1. Why is the first time BFS reaches T already the shortest route?
    • Because it explores in rings of increasing distance
    • Because it picks the cheapest edge
    • Because it uses recursion
  2. How do you recover the route itself?
    • Sort the visited list
    • Follow parent pointers from the target back to the source
    • Run BFS twice
  3. BFS shortest path is only correct when…
    • The graph is a tree
    • There are no cycles
    • All edges have the same cost