Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Number of Islands

Graphsmedium

Given a grid of `1` (land) and `0` (water), implement `numIslands(grid)` returning the number of islands. Islands connect horizontally or vertically.

Sample tests

Input: numIslands([[1,1,0],[1,0,0],[0,0,1]])
Output: 2
Input: numIslands([[1,1,1],[1,1,1]])
Output: 1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Revisiting cells without marking them counts islands twice.

Learning resources

  • Wikipedia: Graph traversal
Approach & explanation (try first)

DFS/flood-fill from each unvisited land cell counts components in O(rows * cols) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.