Implement island counting with BFS and DFS
BloombergSoftware Engineer · OnsiteLast updated
A Bloomberg Software Engineer onsite coding question: count the number of islands (connected land regions) in an m x n grid under four-directional connectivity. It asks for a linear-time O(m·n) flood-fill plus a second, explicit breadth-first-search implementation, with correctness and complexity analysis, edge-case handling, tests, and a diagonal-adjacency follow-up.
Question
You are given an m x n grid of characters where '1' represents land and '0' represents water. Count the number of distinct islands (connected land regions). Two land cells belong to the same island if they share a side — up, down, left, or right. Cells that touch only at a corner (diagonally) are not connected and count as separate islands.
For example, the grid below contains 3 islands:
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
- Primary solution. Implement
countIslands(grid)using any approach you like, running inO(m·n)time. Explain why it is correct and analyze its time and space complexity. - Explicit BFS version. Re-implement the count using an explicit breadth-first search (an iterative queue, no recursion). State its time and space complexity and compare the trade-offs against your first solution.
- Edge cases. Make sure the solution behaves correctly on: an empty grid (
null/0rows /0columns), an all-water grid, a single-cell grid, a grid that is entirely land, and very large grids. Confirm that diagonally-touching land cells are treated as separate islands. - Testing. Describe (or write) tests that validate the solution on several nontrivial cases, including the examples above.
- Follow-up. Briefly describe how your solution would change if diagonal (8-directional) adjacency also counted as connected.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.