Depth-first search (DFS)

The DFS algorithm will start traversing the graph from the first specified vertex and will follow a path until the last vertex of this path is visited. Next, it is going to backtrack the path and then follow the next path. In other words, it visits the vertices first deep and then wide, as demonstrated in the following diagram:

The DFS algorithm does not need a source vertex. In the DFS algorithm, for each unvisited vertex v in graph G, visit the vertex v.

To visit vertex v, perform the following steps:

  1. Mark v as discovered (grey).
  2. For all unvisited (white) neighbors w of v, visit vertex w.
  3. Mark v as explored (black). ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.