What is Depth-first search?

A way of searching a graph or tree that goes as far as possible along one path and backtracks to try another path when it reaches a dead end. It is implemented with recursion or a stack and is used for maze solving, finding connected components and cycles, and topological sorting. It is abbreviated DFS.

Japanese name: 深さ優先探索

Depth-first search appears in 3 practice questions across 1 topic, including Data Structures and Algorithms.

Field: Data Structures and Algorithms

Try it: questions about Depth-first search

In an undirected graph, the neighbors of each vertex are A: B, C / B: A, D, E / C: A, F / D: B / E: B, F / F: C, E. A recursive depth-first search starts from vertex A. The neighbors are examined in the order listed, and as soon as an unvisited vertex is found, the search moves to it. In what order are the vertices visited?

  1. AA, B, C, D, E, F
  2. BA, B, D, E, C, F
  3. CA, B, D, E, F, C
Show answer and explanation

Answer: C. A, B, D, E, F, C

From A the search moves to B, then to D, the first unvisited neighbor of B. D's only neighbor, B, is already visited, so it returns to B and moves on to E, then from E to the unvisited F, and from F to its neighbor C. The order is therefore A, B, D, E, F, C. A, B, C, D, E, F is the breadth-first search order, which visits vertices nearest-first. A, B, D, E, C, F turns back from E without going to the unvisited F, so it is not a depth-first order.

Depth-first search in the explanations

Questions that mention Depth-first search (3)

  1. In an undirected graph, the neighbors of each vertex are A: B, C / B: A, D, E / C: A, F / D: B / E: B, F / F: C, E. A recursive depth-first search starts from vertex A. The neighbors are examined in the order listed, and as soon as an unvisited vertex is found, the search moves to it. In what order are the vertices visited?
  2. In a graph whose edges have no weights, you want to find the smallest number of edges from a starting vertex to every other vertex. Which pair of search method and data structure is suitable?
  3. Tasks A to E have the ordering constraints “A before C”, “B before C”, “C before D”, “B before E” and “E before D”. Which order satisfies all the constraints (a result of topological sorting)?

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

Related terms

Breadth-first search Queue Recursion Stack Binary heap Binary search Binary search tree Dijkstra's algorithm Dynamic programming Greedy algorithm

Back to the glossary