Question presented to candidate: "You are given a 2-D grid of '1's (land) and '0's (water). An island is a group of land cells connected horizontally or vertically. Write a Python function that returns the number of islands."
What a strong answer should cover:
- Model the grid as an implicit graph; an island is a connected component of land cells.
- Scan every cell; each unvisited land cell starts a new island, then flood-fill (DFS or BFS) to mark the whole island.
- Mark cells as visited before (or as) you explore them, either by sinking them in place or with a visited grid.
- O(rows ร cols) time; O(rows ร cols) worst-case space for the recursion or the explicit stack.
- Python details: the default recursion limit of 1000 makes recursive DFS fail on a mostly-land grid as small as 32 ร 32, so an explicit list stack (or
collections.dequeBFS) is the robust version; strings are immutable, so convert rows to lists before sinking.
Clarifying questions expected:
- Do diagonal cells count as connected?
- May I modify the input grid?
- How large can the grid be?
Code / implementation expected: Yes โ a nested loop plus a flood fill (recursive sink and an iterative version), in Python.