FrontendInterviews.dev

Loading problem…

284. Number of Islands

Medium•
Acceptance: 84.62%
•
🔓3/3 Pro unlocks today

Given an m x n 2D grid of "1" (land) and "0" (water), return the number of islands.

An island is formed by connecting adjacent lands horizontally or vertically.

Requirements

Implement:

function numIslands(grid) {}

Example Usage

numIslands([
  ['1', '1', '0'],
  ['1', '0', '0'],
  ['0', '0', '1'],
]); // 2

numIslands([
  ['0', '0'],
  ['0', '0'],
]); // 0

Constraints

  • 1 <= m, n <= 300
  • Grid contains only "0" and "1"
  • Use DFS or BFS traversal