20

Depth-First Search (DFS) and Breadth-First Search (BFS)

When we look at graphs (or trees), we often see this nice collection of nodes with the entire structure fully mapped out (Figure 20-1).

Images

FIGURE 20-1

Our example graph

In real-world scenarios, this fully mapped-out view is the final result of our code having fully explored the graph. When we encounter a graph for the first time, Figure 20-2 is what our computers see.

Images

FIGURE 20-2

Exploring a graph at the beginning

It is an unknown, blank slate. We have to actively explore our graph ...

Get Absolute Beginner's Guide to Algorithms: A Practical Introduction to Data Structures and Algorithms in JavaScript 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.