Day 20: Graph Traversals - BFS and DFS
Graph Traversals - BFS and DFS#
Welcome to Day 20 of our 60 Days of Coding Algorithm Challenge! Today, we’ll dive into two fundamental graph traversal algorithms: Breadth-First Search (BFS) and Depth-First Search (DFS). These algorithms form the basis for many more complex graph algorithms and are essential for solving a wide range of problems.
Introduction to Graph Traversals#
Graph traversal refers to the process of visiting (checking and/or updating) each vertex in a graph. The order in which the vertices are visited defines the traversal algorithm. The two most common traversal algorithms are:
- Breadth-First Search (BFS)
- Depth-First Search (DFS)
Breadth-First Search (BFS)#
BFS explores a graph level by level. It visits all the neighbors of a vertex before moving to the next level neighbors.
Algorithm:#
- Start from a chosen source vertex and add it to a queue.
- Visit the vertex at the front of the queue and remove it.
- Add all unvisited neighbors of this vertex to the queue.
- Repeat steps 2-3 until the queue is empty.
Implementation:#
1from collections import deque
2
3def bfs(graph, start):
4 visited = set()
5 queue = deque([start])
6 visited.add(start) …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating