Solve Number of Islands
Company: Bloomberg
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of graph and grid traversal concepts, specifically identifying connected components in a binary matrix and familiarity with traversal strategies such as BFS and DFS.
Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300 (an empty grid is also accepted and returns 0)
- grid[i][j] is '0' or '1' (string characters, not integers)
Examples
Input: ([['1','1','1','1','0'],['1','1','0','1','0'],['1','1','0','0','0'],['0','0','0','0','0']],)
Expected Output: 1
Explanation: All the '1's form one connected blob, so there is exactly one island.
Input: ([['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']],)
Expected Output: 3
Explanation: Three separate clusters: the 2x2 block top-left, the lone '1' in the middle, and the two adjacent '1's bottom-right.
Input: ([],)
Expected Output: 0
Explanation: Empty grid corner case — no cells means no islands.
Input: ([['0']],)
Expected Output: 0
Explanation: A single water cell forms no island.
Input: ([['1']],)
Expected Output: 1
Explanation: A single land cell is one island.
Input: ([['1','0','1','0','1']],)
Expected Output: 3
Explanation: In a single row, the three '1's are separated by water, giving three islands (diagonal/horizontal-gap separation).
Input: ([['1'],['0'],['1'],['0'],['1']],)
Expected Output: 3
Explanation: In a single column, the three '1's are separated by water rows, giving three islands.
Hints
- Scan every cell. The first time you hit an unvisited '1', you've found a new island — increment the counter and launch a BFS from that cell.
- During BFS, mark each land cell as visited the moment you enqueue it (set it to '0' or use a visited set) so it is never counted or enqueued twice.
- Only move in the four cardinal directions (up/down/left/right). Diagonal neighbors do NOT connect islands.
- Guard the boundaries: before reading a neighbor, check 0 <= nr < rows and 0 <= nc < cols. Handle the empty-grid corner case up front by returning 0.