Breadth-first search (BFS) and depth-first search (DFS) are the two basic ways to traverse a graph or a tree. Both visit every reachable vertex once in O(V + E) time, but they explore in a different order, and that order makes each one better suited to different problems. This page recaps both and then compares them.
What is Breadth First Search (BFS)?
BFS explores a graph in layers. Starting from a source vertex, it visits all neighbours of the source, then all vertices two edges away, and so on, using a FIFO queue to hold the vertices that are waiting to be processed.

Because vertices are reached in order of distance, BFS finds shortest paths (by number of edges) in unweighted graphs. The edges it uses form a BFS tree of the vertices reachable from the source.
What is the Depth First Search (DFS) Algorithm?
DFS follows one path as far as it can go. It moves to an unvisited neighbour, then to an unvisited neighbour of that vertex, and so on; at a dead end it backtracks to the most recent vertex with unvisited neighbours. It is usually written recursively, or with an explicit stack.
Difference between BFS and DFS
| Characteristic | BFS (Breadth First Search) | DFS (Depth First Search) |
|---|---|---|
| Order of visiting | Layer by layer: all vertices at distance 1, then distance 2, and so on. | Along one path as deep as possible, then backtrack. |
| Data structure | Queue (FIFO). | Stack (LIFO), usually the recursion call stack. |
| Shortest paths | Finds shortest paths (fewest edges) in an unweighted graph. | Does not guarantee shortest paths. |
| Time complexity | O(V + E) with an adjacency list; O(V2) with a matrix. | O(V + E) with an adjacency list; O(V2) with a matrix. |
| Extra memory | O(V) in the worst case; in practice proportional to the widest layer, which can be large for bushy graphs. | O(V) in the worst case; in practice proportional to the deepest path, which can be large for long chains. |
| Completeness on huge or infinite graphs | Finds a target at the smallest depth first, so it is preferred when the answer is likely to be close to the start. | Can wander down a very long branch before finding a nearby target. |
| Typical uses | Shortest paths in unweighted graphs, level-order traversal of trees, bipartite checking, finding all vertices within k steps. | Cycle detection, topological sorting, connected and strongly connected components, backtracking puzzles, preorder/inorder/postorder tree traversals. |
| Backtracking | No explicit backtracking; the queue holds the frontier. | Backtracks when a dead end is reached. |
Neither search is faster in general: both do O(V + E) work. Choose BFS when distance from the start matters, and DFS when you need to explore whole branches or reason about the structure of the graph.