LeetCode 200. Number of Islands
🧩 Problem Description
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return the number of islands.
An island is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are surrounded by water.
💬 Examples
Example 1
1 | Input: grid = [ |
Example 2
1 | Input: grid = [ |
💡 Intuition
This is a connected components counting problem on a grid.
- Each
'1'
is land. - We can run DFS or BFS from every unvisited
'1'
. - Every time we start a new search, it means we found a new island.
- Mark visited cells as
'0'
to avoid double counting.
🔢 Java Code (DFS)
1 | class Solution { |
🔄 Alternative Approaches
- BFS with Queue instead of recursion.
- Union-Find (Disjoint Set Union): Treat each land cell as a node, union adjacent lands, then count distinct sets.
⏱ Time and Space Complexity
- Time Complexity: O(m × n) — each cell is visited at most once.
- Space Complexity:
- O(m × n) worst-case recursion depth (DFS stack).
- O(min(m, n)) for BFS queue.
- Union-Find requires O(m × n) extra memory.
✍️ Summary
- Classic flood fill problem.
- Each DFS/BFS call explores one island fully.
- Count how many times we start a new DFS/BFS.
Related problems
lc-695
— Max Area of Islandlc-463
— Island Perimeterlc-733
— Flood Fill