Recursive and iterative DFS
Standard · Write code · about 12 min
Return the nodes in the order depth-first search visits them from source. Try neighbors in the order buildAdjacency(graph) lists them (edge-list order, both directions for undirected edges). Write it recursively, then again with an explicit stack.
In Python, build the adjacency lists from graph["edges"] yourself.
Example 1
Input:
[{"n":5,"edges":[[0,1],[0,2],[1,3],[2,3],[3,4]],"directed":false},0]
Output:
[0,1,3,2,4]
From 3 the search tries 2 before 4.
Example 2
Input:
[{"n":5,"edges":[[0,1],[1,2],[2,0],[0,3],[3,4]],"directed":true},0]
Output:
[0,1,2,3,4]
Directed edges only go one way.
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ source < n
- Edges are [u, v] pairs;
graph.directedtells whether they are one-way.
Learn the idea first: Depth-first search, a visual lesson.
More Depth-first search problems
- DFS order Warm-up
- Back edge Warm-up
- Is there a path? Standard
- Cycle reachable from a node Standard
- All paths from source to target Challenge