Depth-First Search (DFS) explained: graph traversal, recursive & iterative implementations, cycle detection, and interview practice.
Depth-First Search (DFS) is a foundational graph traversal technique that dives deep into a graph branch before backtracking. It powers key graph algorithms like topological sorting, strongly connected components, cycle detection, and maze solving.
DFS can be implemented recursively using the call stack or iteratively using an explicit Stack data structure. A visited set prevents infinite loops in cyclic graphs.
Choose an unvisited vertex as the entry point and mark it as visited.
Recursively visit the first adjacent neighbor that has not been marked as visited yet.
When a node has no unvisited adjacent neighbors, backtrack to the previous node in the recursion call stack.
If any vertices remain unvisited, start a fresh DFS traversal from them to visit all disconnected graph components.
1function dfs(graph, startNode) {2 const visited = new Set();3 const result = [];4 5 function traverse(node) {6 if (!node || visited.has(node)) return;7 8 visited.add(node);9 result.push(node);10 11 const neighbors = graph[node] || [];12 for (const neighbor of neighbors) {13 if (!visited.has(neighbor)) {14 traverse(neighbor);15 }16 }17 }18 19 traverse(startNode);20 return result;21}22 23// Example usage:24// const graph = { A: ['B', 'C'], B: ['D'], C: ['E'], D: [], E: [] };25// dfs(graph, 'A'); // ['A', 'B', 'D', 'C', 'E']Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Interactive node & edge state graph traversal explorer
Test your understanding of Depth-First Search (DFS) complexity and step mechanics.
Q1.Which data structure does Depth-First Search implicitly or explicitly rely on?
Q2.What is the time complexity of DFS on a graph with V vertices and E edges using an adjacency list?
Apply Depth-First Search (DFS) to real coding interview questions.
Count the number of 2D grid islands using DFS graph traversal.
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.