Depth-first search (DFS)

Time complexity: O(V + E).

Result

Examples

How it works

DFS follows one path as far as it can, then backs up to the last fork and tries the next way, using a stack. It finds a path, but rarely the shortest one.

When to use it

Checking if a route exists, generating mazes, and exploring every branch of a tree.

Other algorithms