Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Explain DFS — recursion, stack, when preferred over BFS.

FresherFundamentalsData Structures & Algorithms
Model answer

DFS

Go deep via recursion or explicit stack—detect cycles, topological sort, connected components.

java
void dfs(int u, Map<Integer, List<Integer>> g, Set<Integer> vis) {
  vis.add(u);
  for (int v : g.getOrDefault(u, List.of())) {
    if (!vis.contains(v)) dfs(v, g, vis);
  }
}
BFS for shortest unweighted; DFS for exhaustive path / backtracking.