Question bankPricingSign in

Island Counter

GraphsMedium1:30

Given a 2D grid where "1" represents land and "0" represents water, count the number of distinct islands. An island is a group of adjacent land cells connected horizontally or vertically (not diagonally).

For example:

1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
-> 3 islands

Explain your approach, including how you track visited cells.

How to approach it

  • Hint 1

    Iterate through every cell. When you find a '1', that's a new island -- then mark all connected land.

  • Hint 2

    DFS or BFS from each unvisited land cell will visit the entire island.

  • Hint 3

    You can mark cells as visited by changing '1' to '0' in-place, or use a separate visited set.

Ready to answer it out loud?

Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.

Practising needs an invite code. Join the waitlist and we’ll send you one.