Depth-first search

As the name suggests, the DFS algorithm traverses the depth of any particular path in the graph before traversing its breadth. As such, child nodes are visited first before sibling nodes. The stack data structure is used to implement the DFS algorithm.

We start by visiting the A node, and then we look at the neighbors of the A vertex, then a neighbor of that neighbor, and so on. Let's consider the following graph in the context of DFS:

After visiting the A vertex, we visit one of its neighbors, B, as shown:

After visiting ...

Get Hands-On Data Structures and Algorithms with Python 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.