Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Which traversal do I run -- BFS or DFS?

Both visit every reachable vertex; which one actually answers your question depends on what you're asking.

Need a shortest path in an unweighted graph, or the fewest hops between two vertices? Reach for BFS. Need a topological order, a strongly connected component, or to classify an edge as tree/back/ forward/cross? Reach for DFS. If you only need "is it reachable at all" or "how many components does this have," either traversal answers it equally well -- pick whichever you already have running.

Reach for BFS

In a graph where every edge counts the same, BFS from a vertex finds the shortest path to every other vertex for free.

BFS explores level by level, so the first time it reaches a vertex is guaranteed to be via a shortest (fewest-edge) path.

Reach for DFS

Lining up the vertices of a directed acyclic graph so every edge points from an earlier vertex to a later one.

A topological order falls straight out of DFS's own finishing-time order, reversed.

The largest groups of vertices in a directed graph where every vertex can reach every other vertex in the same group by following directed edges.

Finding strongly connected components (Chapter 11) is built directly on two passes of DFS.

Either works

Graph settings

Calculator