MediumDepth-First SearchRecursionMatrixFlood Fill

Number of Islands

LeetCode
1 approach, code in all languages

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].length
  • 1 ≤ m, n ≤ 300
  • Each cell is either '0' or '1'
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now