Graph BFS / DFS
O(V + E)
Explore with a queue (BFS) or recursion/stack (DFS), marking visited so you never revisit a node.
0/70 solved
Recognise it
The signal
Grid or graph: islands, flood fill, regions, clone, reachability, or fewest steps on an unweighted / implicit graph.
1Brute force
Try all paths (exponential).
2The observation
Revisiting vertices: a visited set makes the search O(V + E).
3Why it works
Each node is marked visited once, when first reached; BFS pops nodes in non-decreasing distance.
Reach for it when
- +Grid problems: islands, flood fill, regions, surrounded areas, shortest path in a maze.
- +Reachability / connectivity / count components, clone a graph.
- +Unweighted shortest path (BFS), or 'spread from multiple sources simultaneously' (multi-source BFS).
Not when
- ×Edges have differing non-negative weightsuse Dijkstra; Bellman-Ford if weights can be negative
- ×Weights are only 0 and 1use Deque BFS
- ×Dependency order on a DAGuse Topological sort
- ×Repeated merging / online connectivity queries (no paths needed)use Union-Find
- ×Edges get deleted onlineuse Reverse the deletions offline, then Union-Find
- ×You must use every edge once, not visit every vertexuse Euler path
- ×You think DFS gives the shortest pathuse BFS: DFS finds a path, not the fewest edges
Intuition
A graph is dots (nodes) joined by lines (edges). A grid is just a graph in disguise — each cell is a node, edges go to its up/down/left/right neighbours. "Number of islands", "flood fill", "rotting oranges" are all grid graphs.
Read the full intuition
Traversal = visit every reachable node without going in circles. The only new idea versus trees is a visited set, because graphs have cycles and a tree doesn't — without it you'd loop forever.
Two engines, same job:
- BFS (queue, level by level) → use when you want the shortest number of steps (unweighted shortest path, "minimum minutes to rot all oranges").
- DFS (recursion/stack, dive deep) → use when you just need to reach / count / fill a whole region (count an island, flood fill).
Counting connected regions (Number of Islands) is the template move: loop every cell; when you hit an unvisited land cell, that's a new island → run a flood (BFS or DFS) that marks the entire region visited so you never recount it; +1 to the count.
Key idea
Mark a node visited the instant you enqueue/enter it, not when you leave — otherwise it gets added multiple times before it's processed, and you double-count.
Why it costs what it costs
Time O(V + E). each node and each edge is examined a constant number of times (for a grid, V = R·C cells and 4 edges each).
Space O(V). visited set plus the queue/recursion stack, each up to the number of nodes.
Practice
- Flood FillFoundationFoundationAmazon, MicrosoftEasy
- Number of IslandsApply it · Count components.Apply itAmazon, UberMedium
- Max Area of IslandOne change · Measure each component.One changeGoogle, UberMedium
- Surrounded RegionsTwists · Decide by what is NOT reachable from the border.TwistsGoogle, AmazonMedium
- Rotting OrangesBranches · Many simultaneous sources; time = BFS layers.BranchesAmazon, UberMedium
- Pacific Atlantic Water FlowBranches · Reachability to two targets.BranchesGoogle, AmazonMedium
- Clone GraphBranches · Copy a graph structure.BranchesMeta, AmazonMedium
- Word LadderCombine · Graph is implicit and built from patterns.CombineAmazon, UberHard
- Bus RoutesAdvanced · Nodes should be routes, not stops.AdvancedUber, GoogleHard
- Shortest Path Visiting All NodesMastery checkMastery checkHard
- Island PerimeterMeta, AmazonEasy
- 01 MatrixGoogle, UberMedium
Pitfalls
Classic bugs
- !Marking visited on dequeue: the same node enters the queue many times (TLE, double counts). Mark on enqueue.
- !Indexing before bounds check: test
0<=nr<R and 0<=nc<Cbefore readinggrid[nr][nc]. - !Multi-source BFS (Rotting Oranges): seed the queue with all sources, BFS once; don't BFS per source.
- !Recursive DFS on a huge grid can stack-overflow: use an explicit stack or BFS when R·C is large.
- !Overwriting the grid as the visited marker saves memory, but only if the caller allows mutating input.
Looks like it, isn't
- Reconstruct Itinerary needs Eulerian Path / Circuit (Hierholzer)
Why
Every ticket (edge) must be used exactly once: Hierholzer, not plain DFS with backtracking. source ↗ - Path With Minimum Effort needs Dijkstra (Weighted Shortest Path)
Why
Cost is the max edge on the path: minimax Dijkstra (or binary search + BFS, or union-find). - Swim in Rising Water needs Dijkstra (Weighted Shortest Path)
Why
Minimax over cell heights; plain BFS ignores the cost. - Evaluate Division needs Union-Find (Disjoint Set)
Why
DFS per query works; weighted union-find answers each query in near O(1). - Minimum Time to Visit a Cell In a Grid needs Dijkstra (Weighted Shortest Path)
Why
Arrival times vary per cell and waiting changes time by 2 (back-and-forth), so it is Dijkstra with a parity correction, not BFS. source ↗ - Longest Cycle in a Graph needs Functional / Successor Graphs
Why
Each node has at most one outgoing edge, so the graph is functional: walk each component once with visit timestamps. source ↗ - Number of Good Paths needs Union-Find (Disjoint Set)
Why
Process vertices by increasing value, union with neighbours of lower or equal value, and count equal-valued vertices per root (Kruskal-style). source ↗ - Minimum Number of Days to Disconnect Island needs Bridges & Articulation Points (low-link)
Why
The answer is always <= 2: 0 if already disconnected, 1 if an articulation cell exists (editorial: Tarjan), else 2. source ↗
Go deepervariants and techniques · 12 combinations · interviewer follow-ups · resources
Variants and techniques
- Multi-source BFSSeed the BFS queue with all sources at distance 0 so one pass gives every cell's distance to its nearest source.
- BFS/Dijkstra on an Augmented State GraphMake each node (vertex, extra state) — keys held, stops used, coupon used, visited mask — and run BFS/Dijkstra on that larger graph.
- Bipartite Check / 2-ColouringBFS/DFS colouring with alternating colours; a conflict means an odd cycle and the graph is not bipartite.
- Bridges & Articulation Points (low-link)In one DFS compute low[v] (earliest discovery time reachable via one back edge) to find edges/vertices whose removal disconnects the graph.
- Eulerian Path / Circuit (Hierholzer)A walk using every EDGE exactly once exists iff degree conditions hold; Hierholzer's algorithm builds it in O(E) by splicing cycles.
- Functional / Successor GraphsEvery node has exactly one outgoing edge, so each component is a cycle with trees hanging off it; reason about tails, cycles, and k-step successors.
- Maximum Flow / Minimum CutPush flow along augmenting paths in a residual graph; max flow equals min cut, which models assignment, disjoint paths, and separation problems.
- Dominator TreeCP 2400+In a directed graph rooted at s, u dominates v if every s -> v path passes through u. The dominator tree (Lengauer-Tarjan, near-linear) answers 'which vertices lie on every path'. On a DAG, idom(v) is the LCA of v's predecessors, processed in topological order.
- Count regionsLoop cells; flood each new region and increment. Number of Islands, Max Area of Island.
- Flood fillDFS/BFS from a seed, recolour the connected same-colour blob. Flood Fill.
- Multi-source BFSEnqueue all sources at distance 0, expand simultaneously, count levels. Rotting Oranges, 01 Matrix.
- Node graph + cloneAdjacency via map; visited maps original→copy. Clone Graph.
- Reverse / from-bordersStart from edges and flow inward to flip the question. Pacific Atlantic, Surrounded Regions.
- Word/state BFSNodes are strings/states, edges are one-step transforms; BFS for fewest steps. Word Ladder.
Combinations
Binary Search on the Answer+Graph BFS / DFS
minimise the maximum height/effort along a path
- Binary Search on the Answer:
- fixes a threshold on edge/cell cost
- Graph BFS / DFS:
- checks reachability using only allowed cells
Dijkstra (Weighted Shortest Path)+BFS/Dijkstra on an Augmented State Graph
one discount, at most k stops, fuel, keys
- Dijkstra (Weighted Shortest Path):
- weighted shortest path
- BFS/Dijkstra on an Augmented State Graph:
- duplicates vertices per resource state
shortest walk visiting all nodes/keys with n <= 12-20
- Graph BFS / DFS:
- BFS over moves
- Bitmask DP:
- encodes visited set into the state
Tree DFS (Paths & Recursion)+Graph BFS / DFS
nodes at distance k from a target node; infection time from a node
- Tree DFS (Paths & Recursion):
- records parent pointers
- Graph BFS / DFS:
- BFS from the target over an undirected view
All Nodes Distance K in Binary TreeAmount of Time for Binary Tree to Be Infected
Centroid Decomposition+Graph BFS / DFS
count paths of length k; nearest marked vertex queries
- Centroid Decomposition:
- splits paths by their top centroid
- Graph BFS / DFS:
- BFS/DFS collects depths from each centroid
Functional / Successor Graphs+Binary Lifting & LCA
teleporters/successor after k steps; first time reaching b from a
- Functional / Successor Graphs:
- every node has one successor
- Binary Lifting & LCA:
- k-step successor in O(log k)
Maximum Flow / Minimum Cut+Bipartite Matching
pair two groups under compatibility constraints
- Maximum Flow / Minimum Cut:
- the solver (unit capacities)
- Bipartite Matching:
- the model (left-right compatibility)
Multi-source BFS+Graph BFS / DFS
escape before the fire/monsters reach a cell
- Multi-source BFS:
- computes earliest arrival of monsters/fire
- Graph BFS / DFS:
- BFS for the player constrained by those times
0-1 BFS+BFS/Dijkstra on an Augmented State Graph
minimum modifications to make a path exist
- 0-1 BFS:
- 0-cost and 1-cost moves
- BFS/Dijkstra on an Augmented State Graph:
- grid cell plus direction/change state
Minimum Cost to Make at Least One Valid Path in a GridMinimum Obstacle Removal to Reach Corner
Bridges & Articulation Points (low-link)+Graph BFS / DFS
critical connections / necessary roads / cities
- Bridges & Articulation Points (low-link):
- low-link comparison to classify edges/vertices
- Graph BFS / DFS:
- single DFS with timestamps
Critical Connections in a NetworkNecessary RoadsNecessary Cities
Eulerian Path / Circuit (Hierholzer)+Graph BFS / DFS
use all tickets once, construct sequences from overlapping pairs
- Eulerian Path / Circuit (Hierholzer):
- Hierholzer post-order splice and degree checks
- Graph BFS / DFS:
- DFS over edges
Reconstruct ItineraryValid Arrangement of PairsDe Bruijn Sequence
Games on Graphs (retrograde analysis)+Topological Sort+BFS/Dijkstra on an Augmented State Graph
chase game on a graph or grid with possible draws
- Games on Graphs (retrograde analysis):
- labels propagate back from terminal states
- Topological Sort:
- Kahn-style degree counters decide LOSE once every move is known to lose
- BFS/Dijkstra on an Augmented State Graph:
- states are (mouse, cat, turn)
Follow-ups interviewers ask
- 01Edges gain weights? → BFS no longer gives shortest paths; switch to Dijkstra (non-negative) or Bellman-Ford.
- 02Multiple simultaneous sources (e.g. rotting oranges)? → seed the queue with all sources at distance 0 (multi-source BFS).
- 03Grid too large for a visited matrix? → mutate the grid in place as the visited marker, or use bit-packing.
- 04Need shortest path with ≤ k steps or 0/1 weights? → BFS variants (0-1 BFS with a deque) before reaching for Dijkstra.
State table
| step | queue (frontier) | dequeue | newly seen | dist |
|---|---|---|---|---|
| 0 | [s] |
s | a, b | 1 |
| 1 | [a,b] |
a | c | 2 |
| 2 | [b,c] |
b | (none) | — |
| 3 | [c] |
c | t | 3 (target) |