BFS vs DFS is about the order of visiting nodes. BFS goes level by level, like ripples in water. DFS goes as deep as it can on one path, then comes back and tries another. If all edges have equal cost and you need the shortest path, choose BFS. If you need to explore full paths or find cycles, DFS is often easier.
BFS means breadth-first search. DFS means depth-first search. A node is a point in a graph. An edge is a link between two nodes.
Verdict: the BFS vs DFS difference in one table
| Point | BFS | DFS |
|---|---|---|
| Visit order | Nearest nodes first | One deep path first |
| Usual helper | Queue | Recursion or stack |
| Time, adjacency list | O(V + E) | O(V + E) |
| Worst-case extra space | O(V) | O(V) |
| Memory is heavy when | Graph is wide | Graph is deep |
| Shortest path, equal edge cost | Yes | Not in general |
| Common uses | Fewest steps, level order | Cycles, topological sort, backtracking |
V is the number of nodes and E is the number of edges. An adjacency list stores the neighbours of each node. If you use a full V by V matrix, both searches take O(V²).
The helper sets the order. A queue is first in, first out. A stack is last in, first out. See stack vs queue if you need that idea first.
BFS vs DFS in graph: the same example
Use this undirected graph. Each node lists its neighbours in order.
| Node | Neighbours |
|---|---|
| A | B, C |
| B | A, D, E |
| C | A, F |
| D | B |
| E | B, F |
| F | C, E |
Start at A.
BFS steps:
- Visit A. Add B and C to the queue.
- Visit B. Add D and E.
- Visit C. Add F.
- Visit D, E and F.
The order is A, B, C, D, E, F. Notice the levels. A is zero steps away. B and C are one step away. D, E and F are two steps away.
DFS steps:
- Visit A, then B, then D.
- D has no new neighbour. Step back to B and go to E.
- From E go to F, then from F go to C.
- Nothing new is left. Step back to A.
The order is A, B, D, E, F, C. DFS went through E and F before it reached C, even though C is next to A.
If the neighbours are listed in another order, your output may change. That does not make it wrong.
Java code and real output
This program runs both searches on the graph above.
import java.util.*;
public class GraphSearch {
static Map<String, List<String>> g = new LinkedHashMap<>();
static List<String> bfs(String start) {
List<String> order = new ArrayList<>();
Set<String> seen = new HashSet<>(Set.of(start));
Queue<String> queue = new ArrayDeque<>(List.of(start));
while (!queue.isEmpty()) {
String node = queue.poll();
order.add(node);
for (String next : g.get(node)) {
if (seen.add(next)) queue.offer(next);
}
}
return order;
}
static void dfs(String node, Set<String> seen) {
if (!seen.add(node)) return;
for (String next : g.get(node)) dfs(next, seen);
}
public static void main(String[] args) {
g.put("A", List.of("B", "C"));
g.put("B", List.of("A", "D", "E"));
g.put("C", List.of("A", "F"));
g.put("D", List.of("B"));
g.put("E", List.of("B", "F"));
g.put("F", List.of("C", "E"));
System.out.println("BFS: " + bfs("A"));
Set<String> seen = new LinkedHashSet<>();
dfs("A", seen);
System.out.println("DFS: " + seen);
}
}
The output is:
BFS: [A, B, C, D, E, F]
DFS: [A, B, D, E, F, C]
seen.add(next) returns true only when the node is new. So the code marks a node as it enters the queue. A LinkedHashSet keeps insertion order, which lets us print the DFS order.
The whole graph is connected here. If a graph has separate parts, start the search again from every node not yet seen.
Common mistake: A common mistake beginners make is to mark a BFS node only when it leaves the queue. Then two neighbours can add the same node twice. Mark it when you add it.
BFS vs DFS in data structure problems
These searches appear in many forms in coding tests.
- Tree level order: Use BFS. The queue already gives one level after another.
- Tree height: DFS is short. Find the height of each child, take the larger one and add one.
- Maze with equal steps: Use BFS for the fewest steps. Each open cell is a node, and each move is an edge.
- Number of islands: Either works. Start at a land cell, mark every connected land cell, and count how many times you had to start.
- Course order: If one course must come before another, you need a topological sort. DFS can do it. So can a queue-based method called Kahn's algorithm.
- Cycle check: DFS is common. In a directed graph, reaching a node still on the current path means there is a cycle. In an undirected graph, ignore the edge back to the parent.
- Permutations and puzzles: DFS with backtracking fits. Make a choice, go deeper, then undo the choice.
For a wider study plan, see data structures and algorithms.
Time, memory and path quality
Both searches look at each reachable node once and check its edges. That is why time is O(V + E). Do not claim one is always faster.
Memory depends on shape. Take a tree where each node has ten children. The fourth level below the root has 10,000 nodes, and BFS may hold all of them. DFS needs only a few nodes for the current path, plus any siblings it has saved.
Now take one long chain with 100,000 nodes. BFS holds one waiting node at a time. Recursive DFS may make 100,000 nested calls and cause a stack overflow. You can write DFS with your own stack to avoid deep recursion.
Path quality differs too. The first time BFS reaches a node, it has used the fewest edges. This is the cheapest path only if each edge has the same cost. If roads have different lengths, use Dijkstra's algorithm for costs that are not negative.
Pro tip: In a problem statement, the words "minimum number of moves" are a strong hint for BFS. The words "all possible paths" or "generate all" are a strong hint for DFS.
BFS vs DFS in AI search
In classic AI, a problem can be shown as states. A state is one situation, such as one position of a puzzle. A move takes you to another state. BFS and DFS are called uninformed search because they have no clue about which state is closer to the goal.
BFS is complete when each state has a limited number of moves. That means it will find a solution if one exists. It finds one with the fewest moves. The price is memory, because it keeps many states.
DFS needs less memory for the path, but it can go down an endless branch. It may also return a long solution. Iterative deepening fixes this by running DFS with depth limit 0, then 1, then 2, and so on. It keeps memory low and still finds the shallowest solution.
If you can estimate the distance to the goal, A* is another choice. This is a different topic from how a machine learning model learns. Our AI vs ML page explains that split.
BFS vs DFS: when to use each
Choose BFS if:
- You need the fewest edges or moves.
- You need level-by-level output.
- The answer is likely close to the start.
Choose DFS if:
- You need to try full paths and undo choices.
- You want to find cycles or connected parts.
- The graph is wide, but not too deep.
Choose either if you only need to visit every reachable node.
For freshers: how to practise and explain it
Draw the six-node graph and write the queue after each BFS step. Then draw the call stack for DFS. Do this without code first. After that, solve one grid problem with both.
Interview note: If you are asked for complexity, name the storage too. Say "O(V + E) with an adjacency list". If the graph is a grid with R rows and C columns, the time is O(R × C).
For more practice, use DSA interview questions. If you are learning Java for development roles, see the Java full stack course at CodeBegun.
Frequently Asked Questions
Which is faster, BFS or DFS?
Does DFS find the shortest path?
Why does BFS use a queue?
Which uses more memory?
Are BFS and DFS used only for trees?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Check the Java Full Stack training details

