← All Exercises

Graph Depth-First Search

advancedjavascript~30min

Background

DFS is used in topological sorting, cycle detection, connected component finding, and maze solving algorithms.

Problem

Write a function that performs DFS on a graph starting from a given node, returning the visited nodes in DFS order.

Input

A graph as an adjacency list object and a starting node.

Output

An array of node values in DFS traversal order.

Sample tests

Sample 1

Input: {A:["B","C"], B:["D"], C:["D"], D:[]}, start="A"
Expected: ["A","B","D","C"]

Your solution

Learning objective

Understand DFS traversal, recursive backtracking, and visited set management for cycle prevention.