Scrivio Interview library
Graph traversalGraphsReported 20 times · 16 min read · updated 14 November 2026

Compare breadth-first search with depth-first search.

1What the two searches do, seen in a maze

Imagine you are standing in a maze drawn on squared paper, and you want to find the door. There are two natural ways to explore. One is to send out helpers in all directions at once: first every square one step away is checked, then every square two steps away, then three, like ripples spreading from a stone dropped in a pond. The other is to pick one corridor and follow it as far as it goes, and only when you hit a dead end, walk back to the last fork and try the next way. Breadth-first search, BFS, is the ripple. Depth-first search, DFS, is the single explorer with a ball of string.

A maze is a graph. A graph is just a set of places, called nodes, joined by connections, called edges. Here each open square is a node, and two squares are joined when they touch side by side. The same two searches work on any graph, a road map, a network of friends, the dependencies between tasks. A traversal means visiting every node we can reach from a start node, each exactly once. The question asks us to compare the two ways of doing it, and that sounds broad, but it comes down to one small difference, which line of waiting places we take from next.

Our maze has three rows and four columns. S, the start, is the top left square. The door D is directly below it. Two walls block the middle of the second row, so the open squares form a ring of ten. Work it by hand. The ripple reaches D in its very first ring, distance 1. The single explorer, if it happens to try right before down, walks along the top, down the right side and back along the bottom, and reaches D only after 9 steps. Both visit every square, but they meet the door at very different times.

PictureThe maze we will search

S is the start, D the door, # a wall. Every other square is open floor, and we may step up, down, left or right.

  1. S...D##.....
    open squares
    10
    shortest way
    1 step

    1The door is one step below S. The only other way there is the long corridor round the walls, which takes 9 steps.

What to assume

Are the edges weighted, so that some steps cost more than others?
We assume not; every step costs one.
How is the graph stored?
Here the neighbours of a square are worked out from the grid; for a general graph we would keep an adjacency list, a list of neighbours for each node, and the code would be the same.
How large can it be?
Large enough that recursion depth matters.

A careful candidate asks a few questions. Are the edges weighted, so that some steps cost more than others? We assume not; every step costs one. How is the graph stored? Here the neighbours of a square are worked out from the grid; for a general graph we would keep an adjacency list, a list of neighbours for each node, and the code would be the same. How large can it be? Large enough that recursion depth matters. And what does the caller need? We show both orders, and the fewest steps, because that is where the difference shows.

2How to spot which traversal a problem needs

A beginner who meets a graph problem often thinks the choice of search does not matter, since both visit everything. For many questions that is true. For some it decides whether the answer is right at all, and the words of the question tell us which.

The first clue is a word like shortest, fewest steps, minimum moves or nearest, in a graph where every step costs the same. That points to BFS, because the ripple finishes every place at distance d before it touches any place at distance d + 1. So the first time it reaches a place, it has found the shortest way there.

The second clue is a phrase like level by level, such as printing a tree one row at a time. That is BFS again, because its rings are the levels.

The third clue is a phrase like all paths, all combinations, does any path exist, detect a cycle, or order the tasks by their dependencies. These point to DFS, because DFS keeps the current path in memory as it goes deeper, and that path is exactly what such questions need to look at or undo.

These clues all belong to the graph traversal pattern. The name says what it is: traversing a graph, visiting its nodes in an organised order, with a list of places we have discovered but not yet explored, called the frontier. The general rule is that BFS keeps the frontier in a queue, like a line at a ticket window, where the oldest arrival is served first, and DFS keeps it in a stack, like a pile of plates, where the newest is taken first. Choose by what the question needs: distances and levels need the queue; paths, cycles and dependency order need the stack.

Some problems look like plain traversals but need something more. If edges have different weights, the fewest edges is no longer the cheapest route, and we need Dijkstra's algorithm, a BFS whose queue is ordered by distance. Counting separate regions, such as islands on a map, works with either search, and the choice comes down to memory, not correctness.

3The honest first attempt, a brute force that tries every path

Suppose we only knew the single explorer, DFS, and were asked for the shortest way to the door. We have just seen that the first path DFS finds can be long, 9 steps when 1 would do. The honest fix is to try every path, not just the first, and keep the shortest. To do that, the explorer must step back off each square on the way back, so that later paths may use it. Trying every possibility this way is called backtracking, and it is a natural first attempt.

Step throughTrying every path to the door, one after another

Numbers count steps along the path being tried. The brute force tries the long way first, because it looks right before down.

  1. 01239##48765
    this path
    9 steps
    best so far
    9

    1The first path tried goes right along the top, down the right side and back along the bottom, reaching the door in 9 steps.

  2. 0...1##.....
    this path
    1 step
    best so far
    1

    2After stepping back off every square, the search tries going down from S and reaches the door in 1 step, so best becomes 1.

Java
static int best = Integer.MAX_VALUE;
// Try every path from (r, c) to the target that never visits a square twice.
static void allPaths(String[] maze, int r, int c, int tr, int tc, boolean[][] onPath, int length) {
if (r == tr && c == tc) { best = Math.min(best, length); return; }
onPath[r][c] = true;
for (int[] m : MOVES) {
int nr = r + m[0], nc = c + m[1];
if (open(maze, nr, nc) && !onPath[nr][nc]) allPaths(maze, nr, nc, tr, tc, onPath, length + 1);
}
onPath[r][c] = false; // step back off this square so other paths may use it
}

On our maze it works. The search tries right first and records 9, then comes back, tries down, records 1, and keeps 1. There are only two paths, because the open squares form a single ring. So where is the problem?

The problem is how fast the number of paths grows. In an open three by three room with no walls there are already 12 different paths from one corner to the opposite one that never repeat a square, and in a four by four room there are 184. Each step up in size multiplies the count, so the time grows exponentially, while the space stays small, one mark per square and one waiting call per step of the current path, O(V) where V is the number of squares.

The waste is easy to name. The search reaches the same square again and again by different routes, and nothing stops it from exploring long routes before short ones. So let us ask the question that leads further. Could we explore squares in order of their distance from S, so that the first visit to a square is already the shortest?

4From trying every path to the ripple of BFS

If we visited squares in order of distance, then the first time we reached a square we would already know its shortest distance, and we could mark it visited for good and never come back. To explore in order of distance we need a line of waiting squares that hands them back in the order they were found, and that is a queue, first in, first out, like the line at a ticket window.

Here is how the line works. We put S in the queue with distance 0. Then, again and again, we take out the square at the front, and every open neighbour that has no distance yet gets the front square's distance plus one and joins the back of the queue. All squares at distance 1 join before any square at distance 2, because they are found from S itself, and squares at distance 2 are found only while the distance 1 squares are taken out. So the queue always holds at most two neighbouring rings, and they come out in order.

A beginner usually asks, when should we mark a square as visited, when it joins the queue or when it leaves? Let us see what goes wrong if we wait until it leaves. A square with two neighbours already in the queue would be added twice, once by each, and in a large open room the same square could be queued many times, wasting time and memory. Marking it when it joins means each square enters the queue exactly once. In our code, giving the square its distance is the mark.

And DFS? It is the same loop with a stack in place of the queue, so the newest square is explored first and the search dives. Writing DFS as a method that calls itself for each neighbour does the same thing, because the waiting calls form a stack. Both searches mark each square once and look at each edge from both ends, so both take O(V + E) time, where E is the number of edges. The only difference is which waiting square comes next, and that alone decides what each search guarantees.

5Watching both searches explore the same maze

The picture runs the real program. The left copy of the maze shows BFS: each number is the distance BFS gave the square, squares still waiting in the queue are marked as compared, and the square being taken out is marked now. The right copy shows DFS: each number is the length of the path DFS used to get there. Each frame takes one more step of each search.

Watch where the door gets its number on each side; that moment is the whole comparison.

Step throughBFS spreads in rings while DFS follows one corridor

Left: BFS, each number the distance it gave the cell. Right: DFS, each number the length of the path it walked. Walls are greyed; the empty column only separates the two copies.

  1. S...S...D##.D##.........
    BFS queue
    0,0
    DFS path
    0,0
    door
    not reached

    1Both searches start at S in the top left corner and want the door D, one step below it. The left copy shows BFS, the right copy DFS.

  2. 01..01..1##.D##.........
    BFS takes
    0,0
    BFS queue
    0,1 1,0
    DFS on
    0,1
    DFS depth
    1
    door
    BFS 1, DFS not yet

    2BFS takes S out of the queue and queues both neighbours, right then down, at distance 1. The door already has its distance, 1. DFS steps right only.

  3. 012.012.1##.D##.........
    BFS takes
    0,1
    BFS queue
    1,0 0,2
    DFS on
    0,2
    DFS depth
    2
    door
    BFS 1, DFS not yet

    3BFS takes out 0,1, the oldest waiting cell, and queues 0,2 at distance 2. DFS keeps going right along the top corridor, now 2 steps from S.

  4. 012.01231##.D##.2.......
    BFS takes
    1,0
    BFS queue
    0,2 2,0
    DFS on
    0,3
    DFS depth
    3
    door
    BFS 1, DFS not yet

    4BFS takes out the door cell 1,0 and queues 2,0 below it. DFS is at the top right corner, 3 steps along its path, still far from the door.

  5. 012301231##.D##42.......
    BFS takes
    0,2
    BFS queue
    2,0 0,3
    DFS on
    1,3
    DFS depth
    4
    door
    BFS 1, DFS not yet

    5BFS has finished every cell at distance 1 and now works through distance 2, taking out 0,2. DFS turns down the right side, 4 steps deep.

  6. 012301231##.D##423.....5
    BFS takes
    2,0
    BFS queue
    0,3 2,1
    DFS on
    2,3
    DFS depth
    5
    door
    BFS 1, DFS not yet

    6BFS takes out 2,0 and queues 2,1. Its numbers spread out from S like ripples, the same on both corridors. DFS reaches the bottom right corner.

  7. 012301231##4D##423....65
    BFS takes
    0,3
    BFS queue
    2,1 1,3
    DFS on
    2,2
    DFS depth
    6
    door
    BFS 1, DFS not yet

    7BFS takes out 0,3, the end of the top row. DFS turns left along the bottom corridor, 6 steps from S, the door still not reached.

  8. 012301231##4D##4234..765
    BFS takes
    2,1
    BFS queue
    1,3 2,2
    DFS on
    2,1
    DFS depth
    7
    door
    BFS 1, DFS not yet

    8BFS takes out 2,1. DFS walks on along the bottom row to 2,1, 7 steps deep. Its path still holds every cell it has passed.

  9. 012301231##4D##423458765
    BFS takes
    1,3
    BFS queue
    2,2 2,3
    DFS on
    2,0
    DFS depth
    8
    door
    BFS 1, DFS not yet

    9BFS takes out 1,3 and queues the last cell, 2,3, at distance 5. DFS reaches the bottom left corner, 8 steps from S.

  10. 012301231##49##423458765
    BFS takes
    2,2
    BFS queue
    2,3
    DFS on
    1,0
    DFS depth
    9
    door
    BFS 1, DFS 9

    10BFS takes out 2,2; its neighbour 2,3 is already queued, so nothing new is added. DFS goes up into the door cell at last, by a path of 9 steps.

  11. 012301231##49##423458765
    BFS takes
    2,3
    BFS queue
    empty
    DFS on
    backing up
    DFS depth
    9
    door
    BFS 1, DFS 9

    11BFS takes out 2,3 and the queue is empty, so it stops. Both searches have visited all 10 open cells, but only BFS says the door is 1 step away.

Read the first two frames back. When BFS takes out S, it queues both neighbours at once, so the door gets distance 1 in the very first step. DFS, in the same first step, only moves right, because it follows the first open neighbour and dives.

In the middle frames, look at the BFS numbers. They grow evenly along both corridors, 2 and 2, then 3 and 3, then 4 and 4, like ripples meeting on the far side. The queue never holds more than two squares here, one from each corridor. On the DFS side the depth climbs by one each frame as it walks round the ring, and in the tenth frame it finally steps into the door square with a path of 9.

In the last frame both have visited all ten open squares, the same amount of work. But BFS knows the door is 1 step away, and DFS only knows one path of 9 steps. That is why DFS is the wrong tool for fewest steps, and why BFS is the right one.

6Both searches in Java

Here is the full program. open checks that a square is inside the maze and not a wall. bfs returns the fewest steps from the top left square to every square, with -1 where it cannot be reached. dfs records the length of the path DFS happened to use, so we can see the difference. main prints the door's distance from both, the whole BFS table, a walled-off square, and a one-square maze.

Java
import java.util.*;
public class MazeSearch {
static final int[][] MOVES = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // right, down, left, up
static boolean open(String[] maze, int r, int c) {
return r >= 0 && r < maze.length && c >= 0 && c < maze[0].length() && maze[r].charAt(c) == '.';
}
// Breadth-first: fewest steps from (0, 0) to every open cell, -1 if it cannot be reached.
static int[][] bfs(String[] maze) {
int[][] dist = new int[maze.length][maze[0].length()];
for (int[] row : dist) Arrays.fill(row, -1);
Deque<int[]> queue = new ArrayDeque<>();
dist[0][0] = 0;
queue.offer(new int[] {0, 0});
while (!queue.isEmpty()) {
int[] cell = queue.poll(); // the cell that has waited longest
for (int[] m : MOVES) {
int r = cell[0] + m[0], c = cell[1] + m[1];
if (open(maze, r, c) && dist[r][c] == -1) { // mark when queued, never twice
dist[r][c] = dist[cell[0]][cell[1]] + 1;
queue.offer(new int[] {r, c});
}
}
}
return dist;
}
// Depth-first: follow one corridor as far as it goes, then back up.
// steps[r][c] is the length of the path DFS happened to use to reach the cell.
static void dfs(String[] maze, int r, int c, int depth, int[][] steps) {
steps[r][c] = depth;
for (int[] m : MOVES) {
int nr = r + m[0], nc = c + m[1];
if (open(maze, nr, nc) && steps[nr][nc] == -1) dfs(maze, nr, nc, depth + 1, steps);
}
}
static int[][] dfsSteps(String[] maze) {
int[][] steps = new int[maze.length][maze[0].length()];
for (int[] row : steps) Arrays.fill(row, -1);
dfs(maze, 0, 0, 0, steps);
return steps;
}
public static void main(String[] args) {
String[] maze = {"....", ".##.", "...."};
System.out.println(bfs(maze)[1][0]); // 1
System.out.println(dfsSteps(maze)[1][0]); // 9
System.out.println(Arrays.deepToString(bfs(maze))); // [[0, 1, 2, 3], [1, -1, -1, 4], [2, 3, 4, 5]]
String[] walled = {".#.", "##."};
System.out.println(bfs(walled)[1][2]); // -1
System.out.println(dfsSteps(new String[] {"."})[0][0]); // 0
}
}

Let us read bfs in the order it runs. First every distance is set to -1, which means not reached yet. The start gets distance 0 and joins the queue, an ArrayDeque used from both ends. The while loop runs as long as some square is waiting. queue.poll() takes out the square that has waited longest, which is what makes this breadth-first.

For that square we try the four moves in the order right, down, left, up. A neighbour joins the queue only if it is open and its distance is still -1. Setting its distance at that moment is the visited mark, so no square is queued twice, and its value is the front square's distance plus one. When the queue is empty, every reachable square has its shortest distance.

dfs is shorter because the call stack does the remembering. It writes the current depth on the square, then for each open neighbour not yet reached it calls itself one step deeper. When a call runs out of neighbours it returns, which is the explorer walking back to the last fork.

So main prints 1 for BFS and 9 for DFS at the door, then the table [[0, 1, 2, 3], [1, -1, -1, 4], [2, 3, 4, 5]], where -1 marks the walls. In the walled maze the bottom right square cannot be reached, so BFS leaves it at -1, and a one-square maze gives 0.

7How much they cost, and the cases at the edges

Count on the example first. Each search visited the ten open squares once, and each square looked at its four possible moves, forty checks in all. For a graph with V nodes and E edges, each node is taken out once and each edge is looked at from both ends, so both searches take O(V + E) time. Both need O(V) extra space in the worst case for the marks and the frontier.

What differs is the shape of that memory. BFS holds the current ring of the ripple, which on a wide graph, such as the bottom level of a big tree, can be half of all nodes. DFS holds the current path, which on a long chain can be every node. In Java, recursion that deep can throw a StackOverflowError, so for very deep graphs we write DFS with an explicit ArrayDeque used as a stack.

BFS and DFS compared
AspectBFSDFS
Frontierqueue, oldest firststack or recursion, newest first
Order of visitsring by ring from the startone path deep, then back up
Fewest steps, equal costsyes, the first visit is the shortestno
Memory grows withthe width of the graphthe depth of the graph
TimeO(V + E)O(V + E)
Typical usesshortest route, levels, nearest targetcycles, dependency order, all paths

The edge cases need no special code. A square that cannot be reached keeps distance -1 in BFS and is never visited by DFS, as the walled maze shows. To cover a graph made of separate pieces, we start a new search from every node that is still unvisited. A maze of one square gives 0 at once. Repeated edges or a node joined to itself are harmless, because a visited node is always skipped.

8Follow-up questions

Which would you use for ordering tasks by their dependencies?

Either works, and it helps to see both. With DFS, a task is written down only after every task that depends on it has been finished, and reversing that list gives a valid order. With BFS, called Kahn's algorithm, we count for each task how many tasks it still waits for, start with the tasks that wait for none, and each time one is done, lower the counts of the tasks after it. Kahn's version also notices a cycle: if some tasks never reach a count of zero, they wait on each other in a circle.

What changes when the steps have different costs?

Plain BFS no longer finds the cheapest route, because fewer steps no longer means a smaller total. With costs that are never negative we use Dijkstra's algorithm, which replaces the queue with a priority queue that always hands back the place with the smallest total so far, at O((V + E) log V). When every cost is 0 or 1, a deque where cost 0 steps join the front and cost 1 steps join the back keeps O(V + E).

Why not write DFS with an explicit stack every time?

The recursive version is shorter and reads like the idea, so it is the usual choice for small inputs and in interviews. Its risk is depth: every step deeper waits on Java's call stack, and a path of a few hundred thousand nodes can overflow it. With an ArrayDeque used as a stack, we push the start, and each time we pop a node we push its unvisited neighbours, so the memory lives on the heap and depth is no longer a problem.

9Conclusion

We compared the two searches by the one thing that separates them, the line of waiting places. BFS takes the oldest from a queue, spreads in rings, and so finds the fewest steps when every step costs the same; DFS takes the newest from a stack, dives along one path and backs up, which suits cycles, dependency order and trying every path. Both are O(V + E) time and O(V) space, with BFS memory following the width and DFS memory the depth, while trying every path to find the shortest is exponential. The clue to remember is the word shortest or level in a graph with equal step costs, which means BFS, while all paths, cycle or order usually means DFS.

What to say in the interviewAbout 90 seconds aloud

Open with

Both visit every node reachable from a start exactly once, in O(V plus E) time with an adjacency list, and both mark nodes as visited so nothing is processed twice.

Then, if they want more

The difference is the frontier. BFS uses a queue, so it finishes every node one edge away before any node two edges away, which means the first time it reaches a node it has the fewest-edges path.

So for shortest paths with equal costs, nearest targets or level order, I use BFS, and I mark nodes when they are queued so none is queued twice. DFS uses a stack, usually the call stack through recursion, so it follows one path as deep as it can and then backtracks.

It does not give shortest paths; to get one from DFS I would have to try every simple path, which is exponential. But DFS is natural for cycle detection, topological order, all paths and backtracking.

Memory differs too: BFS holds the current level, so it grows with the width, and DFS holds the current path, so it grows with the depth, and deep recursion can overflow the stack in Java, so for big graphs I write DFS with an explicit ArrayDeque. With weighted edges neither works for shortest paths, and I would switch to Dijkstra.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 20 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare breadth-first search with depth-first search.": https://scrivio-interview-library.netlify.app/data-structures/solutions/compare-breadth-first-search-with-depth-first-search-96ca7e/