DFS and Recursion

Intermediate Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

DFS goes deep: Recursion or explicit stack. Useful for connectivity, cycle detection, and topological sorting in DAGs.

Mark nodes as visited to avoid infinite loops in cycles.

$$O(|V|+|E|)$$

Where used

Cycle detection, topological sorting, Connected Components, maze/constraint search, compiler call graphs. Often uses an explicit stack instead of deep recursion.

Depth

Depth-first search pursues an open branch as far as possible and then returns to the last branching point. Recursion implicitly stores this return state in activation records.

A state array per node prevents re-expansion and makes cycles manageable. With multiple states, active nodes can be distinguished from fully completed nodes, which facilitates cycle detection in directed graphs.

Entry and exit times generate a bracket structure for nested subtrees. This underpins topological sorting, connectivity analysis, and edge classification.

Difficulty levels

  1. Follow recursive search sequences for ordered neighbors.
  2. Use active and completed states for cycle detection.
  3. Connect exit order with topological sorting.

Pitfalls

Excluding only the immediate predecessor is insufficient in general or directed cycles. Large graphs can also exceed the safe recursion depth.

University approvals: 0
Tasks
Question 1

What prevents infinite runs in DFS in graphs with cycles?

Question 2

What is the purpose of a separate state for still active nodes?

Question 3

Check with recursive depth-first search whether a target is reachable.

Hint

A boolean[] stores visit markers per index. Java can iterate with for (int v : list) over a List<Integer>.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Best
Best
BestBuddy