CS With NehalCS With Nehal

DFS (Depth First Search) Simulator

Build interactive graphs and watch DFS plunge down deep paths and backtrack using a visual stack.

Start:A▼
Nodes (V): 7
Edges (E): 6
DFS Stack
Empty
Start
A
B
C
D
E
F
G
Animation Speed — 1000ms

About This Simulation

This DFS simulator lets you build a graph and watch Depth First Search go as deep as it can along one path, then backtrack. The stack is shown on screen so you can follow every push and pop.

Features

  • Draw your own graph or load an example
  • Choose the start node
  • Live DFS stack showing push and pop at every step
  • Discovered, active and finished nodes in different colours
  • Step-by-step playback with speed control

Explanation

Depth First Search (DFS) is a graph traversal algorithm that follows one path as far as possible before backtracking to try another branch. It uses a stack, either explicitly or through recursion, so the most recently discovered node is explored first.

How it works

  1. Push the start node onto the stack.
  2. Pop the top node. If it has already been visited, skip it; otherwise mark it visited.
  3. Push its unvisited neighbours onto the stack.
  4. Repeat until the stack is empty. In the recursive version, the call stack plays the role of the stack.
  5. When a node has no unvisited neighbours, the search backtracks to the previous node on the stack.

Why it matters

DFS is used for cycle detection, topological sorting, finding connected and strongly connected components, solving mazes and puzzles, and as the backbone of backtracking algorithms. It is taught in CSE220 and CSE221.

Frequently Asked Questions

What data structure does DFS use?

DFS uses a stack. In a recursive implementation the program's call stack does this job, which is why DFS is often written as a recursive function.

What is the time complexity of DFS?

O(V + E) with an adjacency list and O(V²) with an adjacency matrix, the same as BFS.

Does DFS find the shortest path?

No. DFS finds a path if one exists, but not necessarily the shortest one. Use BFS for shortest paths in unweighted graphs.

How is DFS used to detect a cycle?

In a directed graph, a cycle exists if DFS reaches a node that is still on the current path (a back edge). In an undirected graph, a cycle exists if DFS reaches a visited node that is not the parent of the current node.

Topics covered

  • Depth First Search
  • Graph Traversal
  • Stack (LIFO)
  • Recursion and Backtracking
  • DFS Tree
  • Cycle Detection

Tags

  • dfs
  • stack
  • recursion

Related Simulations

Acknowledgements

The Person Behind This Simulation

This simulation would not have been possible without his valuable contributions and support. We sincerely appreciate his time, effort, and dedication to the project.

Tahsin Uddin Labib

Tahsin Uddin Labib

  • 4th Year CS Undergraduate Student | BRAC University