Back to Practice
#0151
Count Islands in a Grid
MediumDSA25 min20 XP
Problem
Given a grid of 1s and 0s, count connected groups of 1s using four-direction movement.
Why This Matters
Grid DFS is used in image masks, maps, flood fill, and many interview graph problems.
Function Signature
def count_islands(grid):
Examples
Example 1
Input[[1,1,0],[0,1,0],[1,0,1]]
Output3
The top-left shape is one island; the two isolated 1s are separate islands.
Constraints
- Return the exact requested value.
- Handle empty or small inputs when the prompt allows them.
- Keep the code readable and deterministic.
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 shape is one island; the two isolated 1s are separate islands.
Hidden Test Categories
empty or smallest inputduplicates or repeated valueslarger realistic input