Back to Practice
#0267
Number of Islands
MediumDSA28 min20 XP
Problem
Given a grid of "1" land and "0" water, return the number of islands. Land connects horizontally and vertically, not diagonally.
Why This Matters
Grid DFS/BFS is the bridge between matrix problems and graph traversal.
Function Signature
def num_islands(grid):
Examples
Example 1
Inputgrid = [["1","1","0"],["0","1","0"],["1","0","1"]]
Output3
There is one connected island at top-left, plus two isolated land cells.
Constraints
- Return the exact requested value.
- Handle edge cases cleanly.
- Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Three islands
Input[["1","1","0"],["0","1","0"],["1","0","1"]]
Expected3
Diagonal land does not connect.
All water
Input[["0","0"],["0","0"]]
Expected0
There is no land to start a traversal.
Hidden Test Categories
all landsingle rowempty grid