Count islands with eight-direction adjacency
Company: Snapchat
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's competency in graph traversal algorithms and data-structure trade-offs by counting connected components on a grid with eight-direction adjacency, focusing on BFS/DFS behavior and optional Union-Find approaches.
Constraints
- 1 <= m, n <= 1000 (an empty grid returns 0)
- grid[i][j] is either '1' (land) or '0' (water)
- Cells are 8-directionally connected (orthogonal + diagonal)
- Use an iterative flood fill to avoid recursion-depth limits on large grids
Examples
Input: [['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']]
Expected Output: 1
Explanation: Diagonal links chain the 2x2 block to (2,2) and then to the bottom-right pair, so all land is one island.
Input: [['1','0','1'],['0','1','0'],['1','0','1']]
Expected Output: 1
Explanation: The center cell is diagonally adjacent to all four corners, merging everything into a single island.
Input: [['1','1','1'],['0','1','0'],['1','1','1']]
Expected Output: 1
Explanation: Top and bottom rows connect through the center cell via diagonal adjacency.
Input: [['0','0','0'],['0','0','0']]
Expected Output: 0
Explanation: No land cells, so there are zero islands.
Input: [['1']]
Expected Output: 1
Explanation: A single land cell is one island.
Input: []
Expected Output: 0
Explanation: An empty grid has no islands.
Input: [['1','0','0','1'],['0','0','0','0'],['1','0','0','1']]
Expected Output: 4
Explanation: The four corner land cells are separated by water in all eight directions, giving four isolated islands.
Input: [['1','0','1','0','1'],['0','0','0','0','0'],['1','0','1','0','1']]
Expected Output: 6
Explanation: The middle water row blocks diagonal links between rows, and gaps block links within each row, leaving six single-cell islands.
Hints
- This is the classic 'Number of Islands' problem, but the neighbor set has 8 offsets instead of 4 — add the four diagonals (-1,-1), (-1,1), (1,-1), (1,1).
- Scan every cell; when you find an unvisited '1', increment the count and flood-fill all reachable land from it, marking each visited so it is never counted again.
- Use an explicit stack (or a queue for BFS) rather than recursion so a grid that is almost entirely land does not overflow the call stack.
- For a Union-Find alternative, union each land cell with its land neighbors in only the SE, S, SW, and E directions (a forward-looking half of the 8) to avoid double work, then count distinct roots.