Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Number of Islands

Medium Acceptance 66% Points 30

You are given a 2D grid grid[][] consisting of '1' (land) and '0' (water). Your task is to count the number of islands. An island is formed by connecting adjacent land cells horizontally or vertically. All cells outside the grid are considered water. Return the total number of islands present in the grid.

Examples
Example 1

Example 1

Input: grid = [ ['1'] ]

Output: 1

Explanation: Only one land cell is present, forming one island.

Example 2

Example 2

Input: grid = [ ['1','1','0'], ['0','1','0'], ['0','0','1'] ]

Output: 2

Explanation: One group of connected land forms the first island, and the separate cell forms another.

Example 3

Example 3

Input: grid = [ ['1','1','0','0'], ['1','0','0','1'], ['0','0','1','1'], ['0','0','0','0'] ]

Output: 3

Explanation: There are three separate groups of connected land cells.

Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 = m, n = 300
  • grid[i][j] is either '0' or '1'
Topics
Recursion
Companies
Amazon Microsoft Apple
Added 11 Aug 2026 66% acceptance
Ln 1, Col 1Sign in to save your code
1 1 1 0 1 0 1 1 1
1