Explore a graph level by level
Use arrow keys or buttons to navigate • 24 slides
Breadth-First Search starts at a source vertex and explores in expanding rings:
Drop a stone into still water. Ripples expand outward in concentric circles. BFS radiates outward, reaching everything at distance k before anything at k+1.
BFS guarantees that when you first reach a vertex, you’ve found the shortest path (in edge count) from the source.
Try it: Click any node as the source, then watch BFS expand.
A queue processes vertices in discovery order. All level-1 vertices enqueued before any level-2, so level-1 is fully processed first. That’s what makes it “breadth-first.”
Replace the queue with a stack → you get DFS (goes deep before wide). The data structure is the fundamental difference.
| Color | Meaning |
|---|---|
| WHITE | Undiscovered |
| GRAY | Discovered, in queue |
| BLACK | Fully explored (dequeued) |
Each vertex (except source) is discovered from exactly one vertex. That edge is a tree edge. All tree edges form a spanning tree — the BFS tree.
| Type | Definition |
|---|---|
| Tree edge | Used to discover a new vertex |
| Cross edge | Connects same/adjacent levels, not used for discovery |
The BFS tree encodes shortest paths. The path from any vertex back to the root in the BFS tree IS the shortest path in the original graph.
In undirected BFS, cross edges only connect vertices whose levels differ by at most 1. No edges skip levels.
In an unweighted graph (all edges cost 1), BFS discovers every vertex at the minimum distance from the source.
dist[v] = dist[u] + 1dist[u] is already optimaldist[v] is also optimalBFS does NOT find shortest paths in weighted graphs. Use Dijkstra’s (non-negative weights) or Bellman-Ford (negative weights).
dist[v] = dist[u] + 1 when discovering v from u
Distances are computed when discovered (enqueued), not when processed (dequeued). Each vertex’s distance is set exactly once and never changes.
Follow the parent pointers back to the source
| Vertex | A | B | C | D | E | F | G | H |
|---|---|---|---|---|---|---|---|---|
| parent | — | A | A | B | B | C | C | D |
Each vertex remembers who led it there. Follow the breadcrumbs back to find the shortest route to the source!
Same algorithm, but only follow outgoing edges
Edge A→B does NOT mean you can go B→A. BFS only follows outgoing edges from the current vertex.
In directed graphs, BFS might not reach all vertices from a single source. Unreachable vertices keep dist = ∞.
Each component is an island. BFS explores one island completely. You need a new “boat trip” (new BFS) to reach each separate island.
A single BFS explores only its connected component. Loop through all vertices and start a new BFS for each unvisited one.
Each vertex dequeued once. Each edge checked once per endpoint. Work is distributed, not repeated.
| Representation | BFS Time |
|---|---|
| Adjacency List | O(V + E) |
| Adjacency Matrix | O(V2) |
| Structure | Space | Purpose |
|---|---|---|
| Queue | O(V) | At most V vertices |
| visited[] | O(V) | One bool per vertex |
| dist[] | O(V) | One int per vertex |
| parent[] | O(V) | One ptr per vertex |
| Total | O(V) |
Star graph: center connects to all V-1 vertices. After dequeuing center, all V-1 neighbors are in the queue simultaneously!
"Six degrees of separation" — BFS finds the shortest friendship chain
Click any person as source, then click another as target to find the shortest friendship chain.
Any two people on Earth are connected by at most 6 friendship links. Facebook's 2016 study found the average distance is only 3.57 among 1.59 billion users.
BFS naturally computes the "degree of separation" — it's the foundation for LinkedIn's "2nd connection" and Facebook's "mutual friends."
BFS is everywhere
BFS explores cells level by level — the first time it reaches the exit is guaranteed to be the shortest path. Like flooding the maze with water from the start.
BFS finds pages close to the root first, which are usually the most important. DFS might get lost in deep, low-value chains of links.
Given this graph and source A, what order does BFS visit vertices?
Neighbors processed in alphabetical order. Source = A.
Type the BFS visit order (comma-separated):
This BFS code has a subtle bug — can you find it?
The highlighted lines mark visited when dequeuing. What goes wrong?
What's the problem with marking visited on dequeue?
Mark visited when enqueuing, not when dequeuing. Otherwise, a vertex can be added to the queue multiple times by different neighbors before it's dequeued.
Pick the right algorithm for each scenario
1. Find the shortest route between two subway stations (unweighted edges).
2. Detect if a dependency graph has a cycle (circular dependency).
3. Crawl a website discovering all pages close to the homepage first.
4. Generate a random maze by carving paths through a grid.
Everything you need to know about BFS
| Use BFS When... | Use DFS When... |
|---|---|
| Shortest path (unweighted) | Topological sort |
| Level-order traversal | Cycle detection |
| Nearest neighbor search | Path existence |
| Web crawling (breadth) | Maze generation |
3 questions — check your answers when ready
Q1: Time complexity of BFS with adjacency list?
Q2: When should you mark a vertex as visited?
Q3: BFS guarantees shortest path in...
Step through BFS on this directed graph starting from vertex A
Distance table:
In directed graphs, BFS only follows outgoing edges. Some vertices may be unreachable from the source — their distance stays ∞.
What does this Java BFS code print?
What is printed on the first line (visit order)?
What is the dist array output?