Back to problems Sign in to unlock
Leetcode
Medium
Matrices
Graphs
Union Find
Sets
Google
Amazon
Number Of Islands
Count how many separate islands of land exist in a 2D grid.
Acceptance 100%
Problem Statement
You are given a 2D grid of characters where each cell is either land ('1') or water ('0'). An island is a group of land cells connected horizontally or vertically. Diagonal adjacency does not count.
Return the number of distinct islands in the grid.
Input Format
- A 2D grid of characters or binary values.
- Each cell represents either land or water.
- Cells are connected only in the four cardinal directions.
Output Format
- Return a single integer: the number of connected groups of land cells.
Constraints
- Connectivity is 4-directional only.
- You may assume the grid has at least one row and one column.
- A cell belongs to exactly one island or to water.
Examples
Sample cases returned by the problem API.
Example 1
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 separate islands: one in the top-left, one in the middle, and one in the bottom-right.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.