Loading
Loading
Follow one path to exhaustion, then retreat and try the next.
Go as deep as possible along each branch before backtracking, using recursion or an explicit stack. DFS is the natural fit for questions about connectivity, structure, and whole-path properties — anything where you must fully explore a region before drawing a conclusion about it.
Decide whether your work happens on the way down (pre-order) or on the way back up (post-order). Subtree aggregates and topological order require post-order; that choice is most of the algorithm.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
def count_components(graph): visited = set() components = 0 def explore(node): visited.add(node) for nxt in graph[node]: if nxt not in visited: explore(nxt) for node in graph: if node not in visited: components += 1 explore(node) return components def has_cycle_directed(graph): """Three colours: unvisited, in the current path, fully done.""" UNVISITED, IN_PATH, DONE = 0, 1, 2 state = {node: UNVISITED for node in graph} def explore(node): state[node] = IN_PATH for nxt in graph[node]: # A back-edge to something still on the stack is a cycle. # An edge to a DONE node is merely a re-convergence. if state[nxt] == IN_PATH: return True if state[nxt] == UNVISITED and explore(nxt): return True state[node] = DONE return False return any(explore(n) for n in graph if state[n] == UNVISITED)| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Paint Bucket Region#91 | Easy | Related | |
| Unlock Every Vault#93 | Easy | Primary | |
| Coastline Length#94 | Easy | Primary | |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in| Count the Reefs#97 |
| Medium |
| Primary |
| Study Circles#100 | Medium | Related |
| Can the Curriculum Be Finished?#102 | Medium | Related |
| Draining to Both Coasts#107 | Medium | Related |
| Letter Grid Trail#136 | Medium | Related |