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

DSA
Medium
52.6K views

This problem asks to count connected groups of '1's in a 2D binary grid. It tests DFS/BFS and flood fill algorithms.

Why Interviewers Ask This

Interviewers ask this to test 2D array traversal and component counting skills. They want to see if you can use DFS or BFS to mark visited land cells. It demonstrates graph traversal on grids.

How to Answer This Question

Explain iterating through each cell. When a '1' is found, increment the island count and start a DFS or BFS to mark all connected '1's as visited (e.g., change to '0'). Continue scanning. This ensures each island is counted exactly once. Discuss time complexity based on grid dimensions.

Key Points to Cover

  • Grid iteration
  • DFS/BFS for connectivity
  • Marking visited cells
  • Component counting

Sample Answer

I iterate through every cell in the grid. Whenever I encounter a '1', I know I've found a new island, so I increment my counter. Then, I initiate a depth-first search or breadth-first search to visit all connected '1's,…

Common Mistakes to Avoid

  • Counting the same island multiple times
  • Incorrect boundary checks during traversal
  • Modifying the grid when not allowed

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 89 DSA questions