Skip to main content

Think in Graphs, Then Search Breadth-First

What This Concept Is

A graph is a way to model connections using nodes and edges. Breadth-first search (BFS) explores that graph layer by layer, which makes it useful for path existence and shortest unweighted path problems.

Why It Matters Here

Some problems stop looking like list problems once you draw the relationships. Social networks, bus routes, task dependencies, and family trees all become easier to reason about once the connections are explicit. BFS is often the first useful algorithm on top of that model.

Concrete Example

Imagine a small friendship graph:

you -> alice, bob
bob -> peggy
alice -> claire
claire -> thom

If you want to know whether there is a path from you to thom, BFS checks neighbors in waves:

  1. first-degree neighbors: alice, bob
  2. second-degree neighbors discovered from them
  3. third-degree neighbors after that

Because it uses a queue, it searches the closest layer first. That is why BFS finds the shortest unweighted path.

Common Confusion / Misconception

BFS does not mean "any graph search." The queue is essential. If you replace it with a stack, you change the behavior and can lose the shortest-path guarantee. Another common mistake is assuming BFS solves weighted shortest-path problems. It does not. It solves shortest path by number of steps when each step counts equally.

How To Use It

When a problem sounds like "find the fewest steps," "is there a path," or "what depends on what," try this sequence:

  1. model the situation as nodes and edges
  2. start with the source node's neighbors in a queue
  3. mark visited nodes so you do not repeat work or loop forever
  4. expand outward one layer at a time

If the problem is about dependencies rather than shortest paths, the same graph thinking still helps. You may need an ordering like a topological sort rather than BFS itself.

Check Yourself

  1. Why does BFS need a queue instead of a stack?
  2. What does "visited" protect you from?
  3. When is BFS a good fit, and when is it not?

Mini Drill or Application

Draw one of these as a graph:

  1. a small set of tasks with dependencies
  2. a mini transit map
  3. a friend-of-a-friend network

Then do one of the following:

  • find the shortest path in number of steps, or
  • produce one valid dependency order

Write two or three sentences explaining why your path or ordering is valid.

Read This Only If Stuck