Applied AI Engineer (LLM) coding learning path Level 2 This level · 19 of 31

Number of Islands

Medium Graph traversal DFS BFS

Problem

Given a 2D grid of '1' (land) and '0' (water), return the number of islands. An island is a group of land cells connected four-directionally.

Original: LeetCode 200: Number of Islands.

Examples

Example 1

Input`grid = [["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"]]`
Output`1`

Example 2

Input`grid = [["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"]]`
Output`3`

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 200: Number of Islandsleetcode.com
Previous
Next