DFS Traversal - Problem
Implement depth-first search (DFS) traversal for a graph using both iterative (stack-based) and recursive approaches.
Given an adjacency list representation of an undirected graph and a starting vertex, return a list of vertices visited in DFS order. If multiple neighbors exist, visit them in ascending numerical order.
Requirements:
- Implement both iterative and recursive versions
- Return vertices in the order they are first visited
- Handle disconnected components (only traverse from the given start vertex)
- Visit neighbors in ascending order for consistent output
Input & Output
Example 1 — Connected Graph
$
Input:
graph = {"0": [1, 2], "1": [0, 3, 4], "2": [0, 5], "3": [1], "4": [1], "5": [2]}, start = 0
›
Output:
[0,1,3,4,2,5]
💡 Note:
Starting from node 0, visit neighbors 1 and 2. From node 1, visit neighbors 3 and 4. From node 2, visit neighbor 5. All nodes are reachable.
Example 2 — Partial Graph
$
Input:
graph = {"0": [1], "1": [0, 2], "2": [1], "3": [4], "4": [3]}, start = 0
›
Output:
[0,1,2]
💡 Note:
Starting from node 0, can only reach nodes 1 and 2. Nodes 3 and 4 form a separate component and are not reachable from 0.
Example 3 — Single Node
$
Input:
graph = {"0": []}, start = 0
›
Output:
[0]
💡 Note:
Single isolated node with no neighbors. DFS returns just the starting node.
Constraints
- 1 ≤ number of nodes ≤ 1000
- 0 ≤ number of edges ≤ 2000
- Graph is represented as adjacency list with string keys
- All node values are non-negative integers
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code