Skip to the solution
MediumDSA10 min read

How do you count the number of islands in a grid?

255 views

The problem

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.deque BFS) 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.

  • grid
  • bfs
  • dfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive flood fill: count islands on seven grids
PythonIterative DFS, visited grid, island sizes, 8 directions, large grids

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 110 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Course Schedule: detect cycle with topological sort (Kahn vs DFS)?

Continue