Number of Islands BFS and DFS in DSA Java - Time & Space Complexity
We want to understand how the time needed to find islands grows as the grid size increases.
How does the search through the grid affect the total work done?
Analyze the time complexity of the following code snippet.
public int numIslands(char[][] grid) {
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private void dfs(char[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != '1') {
return;
}
grid[i][j] = '0';
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
This code counts islands by visiting each cell and exploring connected land cells using DFS.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each cell once and exploring connected neighbors via DFS.
- How many times: Outer loops run over all cells (rows x columns). DFS visits connected land cells once each.
As the grid size grows, the total work grows roughly with the number of cells.
| Input Size (n = rows x columns) | Approx. Operations |
|---|---|
| 10 x 10 = 100 | About 100 visits |
| 100 x 100 = 10,000 | About 10,000 visits |
| 1000 x 1000 = 1,000,000 | About 1,000,000 visits |
Pattern observation: The work grows linearly with the total number of cells in the grid.
Time Complexity: O(m x n)
This means the time grows linearly with the total number of cells in the grid.
[X] Wrong: "DFS runs multiple times on the same cells, so time is more than linear."
[OK] Correct: Each cell is visited once and marked visited, so DFS does not repeat work on the same cell.
Understanding this helps you explain how graph traversal works on grids and shows you can analyze nested loops with recursion clearly.
"What if we used BFS instead of DFS? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The problem asks to count distinct islands, where islands are groups of connected '1's horizontally or vertically.Step 2: Clarify what to count
We count how many such groups exist, not their sizes or total land cells.Final Answer:
Count how many separate groups of connected lands (islands) exist -> Option BQuick Check:
Number of islands = count of connected land groups [OK]
- Counting total land cells instead of groups
- Including diagonal connections as connected
- Confusing largest island size with count
Solution
Step 1: Identify correct queue initialization
In Java, Queue is an interface; LinkedList implements Queue. So, Queue queue = new LinkedList<>(); is correct.Step 2: Check other options for errors
Queue queue = new Queue(); uses 'new Queue()' which is invalid (Queue is interface). LinkedList queue = new Queue<>(); reverses types. Queue<int> queue = new ArrayList<>(); uses ArrayList which does not implement Queue.Final Answer:
Queue queue = new LinkedList<>(); -> Option AQuick Check:
Queue interface + LinkedList implementation = correct [OK]
- Trying to instantiate interface Queue directly
- Using ArrayList instead of a Queue implementation
- Wrong generic types for queue elements
char[][] grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};What is the output of a correct Number of Islands BFS or DFS implementation on this grid?
Solution
Step 1: Identify islands in the grid
First island: top-left 2x2 block of '1's. Second island: single '1' at grid[2][2]. Third island: bottom-right 2 connected '1's.Step 2: Count total islands
There are 3 separate islands in total.Final Answer:
3 -> Option DQuick Check:
Count distinct connected land groups = 3 [OK]
- Counting diagonal connections as connected
- Missing single-cell islands
- Counting total '1's instead of groups
void dfs(char[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == '0')
return;
grid[r][c] = '0';
dfs(grid, r + 1, c);
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r, c - 1);
}What is the main bug if the grid is empty (zero rows)?
Solution
Step 1: Analyze grid access for empty grid
If grid has zero rows, grid.length == 0, so grid[0] access causes IndexOutOfBoundsException.Step 2: Identify cause of exception
Accessing grid[0].length without checking grid length first causes error.Final Answer:
IndexOutOfBoundsException when accessing grid[0].length -> Option AQuick Check:
Empty grid means grid[0] invalid access [OK]
- Assuming grid always has at least one row
- Ignoring boundary checks before accessing grid[0]
- Confusing NullPointerException with IndexOutOfBoundsException
Solution
Step 1: Understand BFS traversal per island
BFS visits all connected land cells of one island. Counting visited cells during BFS gives island size.Step 2: Track largest island size
Keep a max variable updated with the largest count found after each BFS traversal.Final Answer:
During BFS, count cells visited per island and track max count across islands -> Option CQuick Check:
Count cells per BFS, track max size [OK]
- Counting total land cells instead of per island
- Assuming BFS cannot count sizes
- Estimating size without traversal
Ready to prove it?
Pass the test and this pattern moves unknown
