AlgoFrames

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.directed tells whether they are one-way.

Learn the idea first: Depth-first search, a visual lesson.

More Depth-first search problems