Back to Practice
#0197
Count Islands in a Grid
MediumDSA25 min20 XP
Problem
Given a grid of 1s and 0s, count how many connected groups of 1s exist using 4-direction movement.
Why This Matters
Grid DFS is the bridge between simple graph traversal and real matrix problems like image regions, flood fill, and map analysis.
Function Signature
def count_islands(grid):
Examples
Example 1
Input[[1,1,0],[0,1,0],[1,0,1]]
Output3
The top-left land cells form one island, and the two isolated bottom cells form two more.
Constraints
- Return the exact requested result.
- Handle common edge cases.
- Keep the solution readable before optimizing.
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 land cells form one island, and the two isolated bottom cells form two more.
Hidden Test Categories
all waterone large islandthin diagonal-only land that should not connect