Back to Practice
#0115

Number of Islands

MediumDSA25 min20 XP

Problem

Given a grid of "1" land and "0" water, return the number of islands using 4-directional connectivity.

Why This Matters

Grid connected-components problems are graph traversal in disguise.

Function Signature

def num_islands(grid):

Examples

Example 1
Input[["1","1","0"],["0","1","0"],["1","0","1"]]
Output3

The top-left connected land is one island; the two isolated cells are separate islands.

Constraints

  • Return the requested value exactly.
  • Handle the stated edge cases.
  • Keep the solution readable.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input[["1","1","0"],["0","1","0"],["1","0","1"]]
Expected3

The top-left connected land is one island; the two isolated cells are separate islands.

Hidden Test Categories
all waterall landempty grid