Breadth-First Search vs Depth-First Search: Key Differences
How breadth-first search (BFS) works
Breadth-First Search (BFS) is a layer-by-layer traversal technique. Starting from the root node (or any chosen starting point in a graph), BFS explores all the immediate neighbors (i.e., nodes at distance 1), then all nodes at distance 2, and so on. This makes it particularly effective for finding the shortest path in unweighted graphs and trees.
The key data structure used in BFS is a queue (FIFO), which ensures nodes are explored in the order they are discovered.
Algorithm:
- Initialize a queue and a visited set (or list) to keep track of visited nodes
- Start by enqueuing the root node and marking it as visited
- While the queue is not empty:
- Dequeue a node
n
from the front - Process node
n
(e.g., print it, check if it’s the goal) - Enqueue all unvisited neighbors (or children in a tree) of node
n
and mark them as visited
- Dequeue a node
- Repeat until all nodes are explored or the goal is found
Example:
Here is an example that shows breadth-first search in action:
With breadth-first search covered, let’s now focus on depth-first search.
Learn Data Structures and Algorithms with Python
Learn what data structures and algorithms are, why they are useful, and how you can use them effectively in Python.Try it for freeHow depth-first search (DFS) works
Depth-First Search (DFS) is a path-oriented traversal technique. It starts from the root (or any chosen node) and explores as far down a branch as possible before backtracking. Unlike BFS, which explores nodes level by level, DFS dives deep into the tree or graph before exploring sibling nodes.
DFS can be implemented in two primary ways:
- Recursively (Implicit stack via function calls)
- Iteratively (Explicit stack)
DFS uses a stack (LIFO) to determine the next node to visit, whether explicitly or through recursion.
Algorithm:
- Initialize a stack (or use recursion) and a visited set/list
- Push the root node onto the stack
- While the stack is not empty:
- Pop the node from the top
- If not already visited:
- Process it (e.g., print or check if it’s the goal)
- Mark it as visited
- Push its children onto the stack
- Repeat until the stack is empty or the goal is found
Example:
Here is an example that shows depth-first search in practice:
Since we’re done discussing both breadth-first search and depth-first search, let’s discover the differences between them.
Differences between breadth-first search and depth-first search
Here are the differences between breadth-first search and depth-first search:
Aspect | BFS | DFS |
---|---|---|
Data structure | Queue | Stack |
Traversal style | Level-by-level | Path-by-path (deepest first) |
Completeness | Complete (if branching factor is finite) | May not be complete in infinite trees |
Optimality | Yes (if all edges have equal cost) | No |
Time complexity | O(b^d) | O(b^d) |
Space complexity | O(b^d) | O(d) |
Best for | Shortest path in unweighted graphs | Exploring entire tree with low memory |
Here, b
is the branching factor and d
is the depth of the shallowest solution.
Now that we’ve gone through the differences between breadth-first search and depth-first search, let’s see how queues and stacks impact search algorithms.
How queues and stacks impact search algorithms
The queue and the stack are the two data structures that can be used for storing nodes in a search frontier. A queue follows “First In First Out” (FIFO) behavior, where the order the data goes in the queue is the order it leaves the queue. This equates to any line you may have stood on to wait for the bus or to grab a cup of coffee.
A stack follows “Last In First Out” (LIFO) behavior which means that the most recent data added will be the first to leave. To get to a book at the bottom of a stack of books you must first remove the books that were more recently placed in the stack. The different behaviors of the queue and the stack will help define the behavior of the two search algorithms in this article.
Let’s move on to the last topic of this article, which is finding the path to the goal in tree traversal.
Finding the path to the goal in tree traversal
It is important to note that it is not enough to find the node with the correct value. Once the goal node is found using either method of tree traversal, you must be able to provide the path of nodes from the root node to the goal node. This can be done in many ways, from saving paths as you search down the tree to working with trees that can supply the path when needed.
The location of the goal node has a significant impact on determining which search algorithm will be able to find the goal first. That is why these approaches are generally used as building blocks for more complex traversal algorithms. With more information on the location of the goal value in the tree, you can optimize the breadth-first search and depth-first search algorithms. Then they become powerful tools that can help you find that file you were looking for.
Conclusion
Breadth-First Search and Depth-First Search offer different strengths depending on the problem at hand. BFS is generally better for finding the shortest path in unweighted graphs, while DFS is more memory efficient and better suited for scenarios where the solution is likely to be deep in the tree. The choice between the two often depends on the structure of the problem space and the desired outcome.
If you want to learn more about search algorithms, check out the How to Implement Search Algorithms with Python course on Codecademy.
Frequently asked questions
1. Which is faster, BFS or DFS?
It depends. BFS is faster when the solution is near the root, while DFS can be faster when the solution is deep and near the beginning of a branch.
2. Is DFS always recursive?
No. DFS can be implemented using a stack (iterative) or recursion. Both achieve the same result.
3. Can BFS and DFS be used on graphs as well as trees?
Yes. Both BFS and DFS work on trees and general graphs. When used on graphs, it’s important to keep track of visited nodes to avoid cycles.
4. Which search guarantees the shortest path, BFS or DFS?
BFS, when all edges have equal weight, guarantees the shortest path to the goal.
5. Can DFS be modified to find the shortest path?
Not in general. DFS isn’t guaranteed to find the shortest path unless all paths are exhaustively compared, which eliminates its efficiency advantage.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Depth-First Search: Conceptual
High-level, language-agnostic introduction to depth-first search with theoretical and practical discussion. - Article
Using ChatGPT for Pair Programming
Learn how to use ChatGPT for pair programming with the driver-navigator approach. Explore BFS and DFS in Python with tips for collaboration and troubleshooting. - Article
Python Stack Data Structure: When and Why to Use it
Learn when and why to use stacks in Python. Understand LIFO, explore real use cases, compare stack implementation methods, and choose between lists, stacks, and queues.
Learn more on Codecademy
- Course
Learn Data Structures and Algorithms with Python
Learn what data structures and algorithms are, why they are useful, and how you can use them effectively in Python.With CertificateIntermediate26 hours - Course
How to Implement Search Algorithms with Python
Finding the data you are looking for in a data set is an important skill: get started with two common approaches.With CertificateIntermediate2 hours - Skill path
Code Foundations
Start your programming journey with an introduction to the world of code and basic concepts.Includes 5 CoursesWith CertificateBeginner Friendly4 hours