Number of Islands
1 approach, code in every language
Problem description
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'
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free