Number Of Islands, Grid BFS/DFS And Backtracking
Asked of: Software Engineer
Last updated
What's being tested
These problems test grid traversal as graph search: modeling cells as vertices, using four-directional adjacency, and finding connected components with BFS or DFS. They also probe backtracking with visited-state restoration, boundary safety, and the ability to justify correctness and or bounded-search complexity.
Patterns & templates
- Flood fill: scan every cell; on unvisited land, increment islands and call
dfsor enqueue it; each cell is processed once, time. - BFS template: use
deque, mark cells visited when enqueuing, and explore(row + dr, col + dc)for four direction vectors. - DFS template: stop on out-of-bounds, water, or visited cells; mark before recursion to prevent cycles and duplicate work.
- In-place visitation: mutate land to water when allowed; otherwise maintain a boolean matrix, trading input preservation for auxiliary space.
- Perimeter counting: each land cell contributes four edges; subtract one for every adjacent land neighbor, or count water/out-of-grid sides directly.
- Backtracking search: mark a cell, recurse to the next character, then unmark on return; reject immediately on bounds, mismatch, or reuse.
- API rectangle search: recursively split inclusive rectangles, prune empty regions using the presence query, and track the strict call budget carefully.
Common pitfalls
Pitfall: Marking a cell after exploring it allows cycles and duplicate queue entries; mark it when discovered, not when removed.
Pitfall: Confusing four-directional connectivity with diagonals, or mixing inclusive rectangle bounds with half-open indexing.
Pitfall: Forgetting to restore
visited[row][col]during backtracking causes one failed path to corrupt all later paths.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
- Compute the perimeter of a single island in a binary gridBloomberg · Software Engineer · Other · easy
- Search for a Word Along Adjacent Cells of a Letter Grid Without Reusing CellsBloomberg · Software Engineer · Technical Screen · medium
- Count Hidden Ships Inside a RectangleBloomberg · Software Engineer · Other · hard
- Solve word path in grid and trapped waterBloomberg · Software Engineer · Technical Screen · easy
- Solve Number of IslandsBloomberg · Software Engineer · Onsite · medium
- Implement island counting with BFS and DFSBloomberg · Software Engineer · Onsite · medium
Related concepts
- BFS, DFS, Graph, And Grid TraversalCoding & Algorithms
- Graph, Grid, BFS/DFS, And Union-FindCoding & Algorithms
- Graph, Grid, And Connectivity AlgorithmsCoding & Algorithms
- DFS/BFS Tree, Graph, And Grid TraversalCoding & Algorithms
- Graphs, Grids, And Connected ComponentsCoding & Algorithms
- Graphs, Grids, And ReachabilityCoding & Algorithms