27 / 75
Use DFS/BFS to flood-fill islands and count connected components.
Example:
Input:
[['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']]Output:
3Common Mistakes:
- Not marking cells as visited (infinite recursion or wrong count)
- Using separate visited array when you can modify grid in-place
- Forgetting to check boundaries in DFS/BFS
- Counting diagonal connections (problem only allows 4-directional)
Notes:
Classic connected components problem. Time O(m*n), Space O(m*n) for recursion stack. Can also solve with Union-Find or BFS.
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Use DFS/BFS to flood-fill islands and count connected components.
Example:
Input:
[['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']]Output:
3Common Mistakes:
- Not marking cells as visited (infinite recursion or wrong count)
- Using separate visited array when you can modify grid in-place
- Forgetting to check boundaries in DFS/BFS
- Counting diagonal connections (problem only allows 4-directional)
Notes:
Classic connected components problem. Time O(m*n), Space O(m*n) for recursion stack. Can also solve with Union-Find or BFS.
27/75
Number of Islands