Introduction
Number of Islands is one of the most popular BFS and DFS interview problems.
You are given:
grid[][] Goal:
Count the number of islands.Island means:
Connected group of 1s. Movement:
UpDown
Left
Right
Example
grid =
[["1","1","0","0","0"],["1","1","0","0","0"], ["0","0","1","0","0"],["0","0","0","1","1"]]
Output:
3Key Observation
Whenever we find:
grid[i][j] == '1' We discovered:
A new island. Perform:
DFS or BFS to visit the entire island.
Algorithm
1. Traverse grid.
2. Find land cell.
3. Increase island count.
4. Run DFS/BFS.5. Mark all connected land.
Dry Run
Input:
11000
11000
0010000011
Island Count:
Island 1
Island 2Island 3
Answer:
3 Approach 1 : DFS
Explanation
For every land cell:
- Visit current cell.
- Mark visited.
- Explore 4 directions.
- Continue recursively.
Practice
Complexity Analysis
DFSTime Complexity: O(m × n)
Space Complexity: O(m × n)
BFS
Time Complexity: O(m × n)
Space Complexity: O(m × n)
Why This Problem is Important