All coding questions

Number of Islands

medium
Blind 75NeetCode 150graphsdfsbfsmatrix

Problem

Given a grid of land and water cells, count the number of islands. An island is a group of land cells connected horizontally or vertically, and is surrounded by water or the grid edge.

Examples

Input: grid with one connected land mass
Output: 1
All land cells are reachable from each other.
Input: grid with three separate land clusters
Output: 3
Three disconnected groups.

Constraints

  • 1 <= rows, cols <= 300
  • Each cell is land or water
Hints(tap to reveal)
  • 1. Each unvisited land cell starts a new island.
  • 2. Flood fill its whole component before moving on.
Optimal approach(spoiler)
  1. Scan every cell in the grid.
  2. When an unvisited land cell appears, increment the island count.
  3. Flood fill from it with DFS or BFS, marking all connected land as visited.
  4. Continue scanning for the next unvisited land cell.
  5. O(rows * cols) time and space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor