Log In Sign Up
Day 20

Day 20: Graph Traversals - BFS and DFS

20/60 Days

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:

  1. Breadth-First Search (BFS)
  2. 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: #

  1. Start from a chosen source vertex and add it to a queue.
  2. Visit the vertex at the front of the queue and remove it.
  3. Add all unvisited neighbors of this vertex to the queue.
  4. 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 …