You are given a 2D grid made of the characters '1' (land) and '0' (water). An island is a maximal group of land cells connected horizontally or vertically, and every island is fully surrounded by water or by the edges of the grid. Diagonal neighbors are not considered connected.
Return the total number of distinct islands in the grid.
Example 1
Input: grid = [ ['1','1','0','0'], ['1','0','0','1'], ['0','0','1','1'], ['0','0','0','0'] ]
Output: 2
The top-left block of land forms one island, and the connected land cells on the right side form the second.
Example 2
Input: grid = [ ['1','0','1'], ['0','0','0'], ['1','0','1'] ]
Output: 4
Each corner cell is isolated by water, so the four land cells count as four separate islands.
Constraints
m == grid.length and n == grid[i].length1 ≤ m, n ≤ 300Each cell is either '0' or '1'See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI