Top 150 InterviewEasy

Number of Islands

Detailed guide and Python implementation for the 'Number of Islands' problem.

Problem Statement

Easy

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Write a function numIslands(grid: List[List[str]]) -> int.

Constraints
  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'

Examples

Example 1
Input
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output
1
Explanation

There is a single island consisting of all connected '1's starting from top-left.

Example 2
Input
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output
3
Explanation

There are three distinct islands separated by '0's.

Need a Hint?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.