Number of Islands in Java: Explanation & Practice
Count number of islands in a 2D grid
Problem summary
Given a 2D grid of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically.
Starter code
public class Main {
public static void main(String[] args) {
char[][] grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
// DFS/BFS from each unvisited '1'
// Mark all connected land as visited
// Count number of DFS/BFS calls
// Print: Islands: 3
}
}Expected output and test cases
- 3 separate islands
Islands: 3
- All connected → 1 island
Islands: 1
- All water → 0
Islands: 0
Hints
- Iterate through grid, when you find '1', start DFS/BFS
- Mark visited cells by changing '1' to '0' or using visited array
- DFS explores all 4 directions: up, down, left, right
- Each DFS/BFS from a new '1' = one new island
Related Data Structures & Algorithms exercises
- Practice Validate Binary Search Tree in Java
- Practice Lowest Common Ancestor in Java
- Practice Clone Graph in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler