Graph Depth First Search Cheat Sheet
You follow one path as far as it goes. At a dead end, you back up and try the next branch.

Earn the full sheet below.
When to use it
- It checks a connection or counts connected groups.
- A grid is a graph, with cells as nodes and borders as edges.
- Order doesn't matter. You only care that a path exists.
What's on the sheet
The recursion is boilerplate. Step 3 shapes the graph.
- Visited Check. Mark a node visited on arrival, before recursing.
- Recurse. A hit bubbles True up; a dead end bubbles False.
- Graph Setup. Here you decide directed or undirected.
Watch out
- visited.add(curr) has to run before you recurse, or two nodes pointing at each other loop forever.
- Directed or undirected is a judgment call. Does one node depend on the other, like in Course Schedule?
How to earn it
Solve half of the Graph Depth First Search problems and the sheet is yours. A free account works fine, and everyone earns their sheets the same way.
Want to see a finished sheet first? Preview the Two Pointers sample.
Every pattern has a sheet. See the full set.