DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on β€’ Originally published at sreekarreddy.com

πŸ”Ž BFS & DFS Explained Like You're 5

Exploring graphs breadth or depth first

Day 105 of 149

πŸ‘‰ Full deep-dive with code examples


The Maze Exploration Analogy

Imagine you're lost in a maze. Two strategies:

Strategy 1 (DFS - Depth First):

  • Pick a path and go as far as possible
  • Hit a dead end? Backtrack and try another route
  • Like following one hallway to the very end

Strategy 2 (BFS - Breadth First):

  • Check all nearby paths first
  • Then move one step deeper on each
  • Like ripples spreading from a stone in water

BFS and DFS are these two exploration strategies!


When To Use Which

Use DFS when:

  • You need to explore all paths
  • Looking for any solution (not necessarily shortest)
  • Checking if something exists

Use BFS when:

  • You need the shortest path
  • Exploring level by level
  • Finding the closest match

How They Work

DFS (goes deep first):

Start at A
    A
   / \
  B   C
 /
D

Visit: A β†’ B β†’ D β†’ C (go deep before siblings)
Enter fullscreen mode Exit fullscreen mode

BFS (goes wide first):

Start at A
    A
   / \
  B   C
 /
D

Visit: A β†’ B β†’ C β†’ D (all of one level before next)
Enter fullscreen mode Exit fullscreen mode

Real-World Examples

DFS used for:

  • Solving puzzles (chess, sudoku)
  • Finding if two people are connected on social media
  • Navigating file systems

BFS used for:

  • Finding shortest route on a map
  • Social network "degrees of separation"
  • Web crawlers exploring links

The Key Difference

  • DFS β†’ Goes deep, uses less memory, might not find shortest path
  • BFS β†’ Finds shortest path, but uses more memory

In One Sentence

BFS explores neighbors first (shortest paths), while DFS explores deeply first (good for exhaustive search).


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)