AlgorithmsIntermediate

Depth-First Search (DFS) in Python

Learn Depth-First Search (DFS) in Python! A super fun guide to exploring graphs, escaping mazes, and backtracking with recursive and iterative code.

Try it yourself

Run this code directly in your browser. Click "Open in full editor" to experiment further.

Loading...

Click Run to see output

Or press Ctrl + Enter

How it works

Ready to go deep? Depth-First Search (DFS) is an amazing algorithm for exploring graphs and trees! ๐Ÿคฟ

How It Works

Imagine you're exploring a giant maze. Instead of looking at every intersection around you (like BFS), you pick one path and run down it as far as you possibly can until you hit a dead end! Once you're completely stuck, you turn around (we call this backtracking) and try the next available path.

To remember where we need to backtrack to, we use a Stack (think of a stack of pancakes ๐Ÿฅž โ€“ Last-In, First-Out).

1. Recursive Approach: This is the elegant way. We just let Python's built-in function-call stack do the heavy lifting for us!

2. Iterative Approach: We build our own Stack using a simple Python list. We just .append() to add, and .pop() to pull from the top!

Like always with graphs, we carry a visited notepad so we don't accidentally run in circles forever! ๐Ÿ˜…

Time and Space Complexity

  • Time Complexity: O(V + E) โ€” V is our vertices (nodes) and E is our edges. We visit every single room and hallway in the maze exactly once!
  • Space Complexity: O(V) โ€” To store our visited notepad and our Stack of path choices.
  • Real World Magic

  • Solving Puzzles: Need to write code to solve a Sudoku puzzle or escape a maze? DFS and backtracking are your best friends!
  • Topological Sorting: Figuring out the order you need to take college classes based on prerequisites.
  • Finding Cycles: Checking to make sure a path doesn't loop back on itself (like detecting a dead-lock in a database).
  • Have fun running the code and tracing the paths it takes! ๐ŸŽ‰

    Related examples

    Keywords: python dfs, depth first search python, dfs algorithm python, graph traversal python, dfs recursion python, backtracking python, python stack dfs