Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Number of Islands

Medium Acceptance 66.00% Points 30.00

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.

Hints
Hint 1
N/A
Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 = m, n = 300
  • grid[i][j] is either '0' or '1'
Companies
Amazon Microsoft Apple
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions