← Back to DSA Animator
Number of Islands LC #200 Medium DFS Flood Fill
Problem

Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

Example 1
Input: grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output: 1
Explanation: All land cells form one connected island.
Example 2
Input: grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
Explanation: Three separate islands.
Constraints: 1 ≤ m, n ≤ 300  |  grid[i][j] is '0' or '1'
Try Examples
Custom:
Approach
DFS Flood Fill: find '1', DFS all connected land, mark visited, count++
Each DFS call sinks the island (marks '1'→'0'). Count = number of DFS calls from main loop
Island Grid
Islands Found
0
Island Colors
#1 Orange
#2 Purple
#3 Yellow
#4 Cyan
#5+ Red
DFS Visited (current island)
Variables
Current (r,c)
Island Count
0
Land Remaining
DFS Depth
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Scan every cell (r, c) in the grid left-to-right, top-to-bottom
2
If grid[r][c] == '1': start DFS, then count++
3
DFS: mark cell as '0' (sunk), recurse on 4 neighbors
4
DFS base: out-of-bounds or already water/visited → return
5
After full scan: return count
Time
O(m × n)
Space
O(m × n)
Why DFS Flood Fill Works

When we encounter an unvisited land cell, we know it belongs to a new island. By DFS-sinking the entire connected component (marking all reachable '1's as '0'), we ensure no cell of that island is counted again. The number of times we trigger a DFS from the outer loop equals exactly the number of islands — one flood-fill per island.