You are given a 2D grid containing '1' (land) and '0' (water). Count the number of islands. An island is formed by connecting adjacent land cells horizontally or vertically (not diagonally). All four edges of the grid are surrounded by water.
Use Depth-First Search (DFS) to explore each island. Iterate through every cell in the grid. When a '1' is found, increment the island counter and perform DFS to mark all connected land cells as visited by changing them to '0'. This process ensures each island is counted exactly once.
The DFS function checks boundary conditions and returns if the cell is out of bounds or is water. It marks the current cell as visited (changes '1' to '0') and recursively explores all four adjacent directions: up, down, left, and right.
Time complexity is O(m * n) where m and n are the grid dimensions, since each cell is visited at most once. Space complexity is O(m * n) in the worst case for the recursion stack when the entire grid is land. This approach is efficient and avoids revisiting cells.
Edge cases include empty grid, grid with no land (return 0), single cell grid, and grid where islands touch the boundary. The algorithm correctly handles all cases by systematically exploring connected components.
Example Input & Output
Single cell island
Empty rows
Three separate islands
No island
All 1s form one island
Algorithm Flow

Solution Approach
Count the number of islands in a 2D grid where '1' is land and '0' is water. Islands are groups of adjacent land cells connected horizontally or vertically. Use DFS: iterate through every cell. When land is found, increment the count and recursively sink the entire island by marking visited cells as '0'. Each cell is visited once.
Modifying the grid to mark visited cells avoids allocating a separate visited array. The DFS explores all four directions recursively, covering the entire island.
Time complexity is O(rows * cols), space complexity is O(rows * cols) for the recursion stack.
Best Answers
class Solution {
int rows, cols;
public int solution(String[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
rows = grid.length; cols = grid[0].length;
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j].equals("1")) { count++; dfs(grid, i, j); }
}
}
return count;
}
void dfs(String[][] g, int i, int j) {
if (i < 0 || i >= rows || j < 0 || j >= cols || g[i][j].equals("0")) return;
g[i][j] = "0";
dfs(g, i-1, j); dfs(g, i+1, j); dfs(g, i, j-1); dfs(g, i, j+1);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
