Data Structures · Visualization
Graph: DFS
Graph
Depth-First Search explores a graph by going as deep as possible down one path before backtracking: it picks a neighbor, dives into that neighbor's neighbors, and keeps going deeper until it hits a dead end, then backs up and tries the next unexplored option. Time: O(V + E). Space: O(V) for the visited set and recursion/stack (worst case).
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: DFS
GraphDepth-First Search explores a graph by going as deep as possible down one path before backtracking: it picks a neighbor, dives into that neighbor's neighbors, and keeps going deeper until it hits a dead end, then backs up and tries the next unexplored option. It's typically implemented with recursion (using the call stack) or an explicit stack, along with a 'visited' set.
How DFS Works
- Start at a chosen node and mark it visited.
- Process the current node.
- For each unvisited neighbor, recursively perform DFS from that neighbor.
- When a node has no unvisited neighbors left, backtrack to the previous node and continue with its remaining neighbors.
DFS Worked Example
Input: DFS from A in graph A-B, A-C, B-D
- Visit A, go to neighbor B
- Visit B, go to neighbor D
- Visit D, no unvisited neighbors, backtrack to B
- B has no more unvisited neighbors, backtrack to A
- A goes to neighbor C, visit C
Output: Visit order: A, B, D, C
Press ▶ Run to watch it step by step.
def dfs(graph, start):
seen = {start}
stack = [start] # stack = dive deep
while stack:
v = stack.pop()
print(v, end=" ")
for nxt in reversed(graph[v]):
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
# Recursive version:
# def dfs_rec(v):
# seen.add(v)
# for n in graph[v]:
# if n not in seen:
# dfs_rec(n)
# example: DFS fromBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
DFS Time & Space Complexity
When to Use DFS
- Detecting cycles in a graph
- Topological sorting of dependency graphs
- Solving mazes and puzzles (exploring all paths)
- Finding connected components
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.