Traversal
Visiting every vertex reachable from a start, systematically. BFS walks
outward in rings using a queue; DFS commits to one branch and plunges using a
stack (explicit, or the call stack via recursion). Both are the same loop with
two knobs - the neighbour function, and how you track visited.
The mechanics, the correctness argument for why BFS's first arrival is always
shortest, and the traps that come from marking visited at the wrong moment
all live on the learn page: Traversal. The
problems below are that engine with one knob turned.
1971. Find if Path Exists in Graph
- Time
- O(V + E)
- Building
graphscans allEedges once.helperthen visits each of theVnodes at most once (guarded byvisited), following each of theEedges at most twice (once per direction) -V + E. - Space
- O(V + E)
graph's adjacency lists store both directions of every edge,O(E), plusvisitedholds up toVnodes and the recursion stack can hold up toVframes on a path graph -V + E.
133. Clone Graph
133Clone Graph
hashmap maps every original node to its clone, built lazily the first time each node is seen - either as the recursion root or as someone's neighbor. visited tracks which nodes have already had their neighbor list wired up, so a node reachable through a cycle is never re-expanded. rec(node) creates the clone (if missing), and - only the first time this node is visited - recurses into each neighbor before appending that neighbor's clone to hashmap[node].neighbors.
- Time
- O(V + E)
- Every node is expanded once (guarded by
visited) and every edge is crossed once. - Space
- O(V)
hashmapandvisitedhold up toVentries; the recursion stack goes as deep as the graph.
2101. Detonate the Maximum Bombs
Each bomb i can trigger bomb j when j sits within bomb i's blast radius - math.dist(a, b) <= bombs[i][2]. That's directed and not necessarily symmetric (i reaching j doesn't mean j reaches i), so build a directed adjacency list adj_list by testing every ordered pair (i, j).
The answer is "starting from the single best bomb, how many bombs eventually detonate" - a reachable-set size, and reachable-set-from-a-node is exactly what DFS computes. Run one DFS per candidate start, using a fresh visited set each time, and keep the largest.
- Time
- O(n^3)
- Building
adj_listchecks every ordered pair,O(n^2). - Running a full DFS from each of the
nbombs isO(n * (n + E)), andEis itselfO(n^2)in the worst case (every bomb in range of every other). - Space
- O(n^2)
adj_listholds up toO(n^2)directed edges in the worst case;visitedand the recursion stack areO(n).