Number of Islands BFS and DFS in DSA C++ - 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 steps taken?
Analyze the time complexity of the following code snippet.
void dfs(std::vector<std::vector<char>>& grid, int r, int c) {
int nr = grid.size();
int nc = grid[0].size();
if (r < 0 || c < 0 || r >= nr || c >= nc || 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);
}
int numIslands(std::vector<std::vector<char>>& grid) {
int count = 0;
for (int r = 0; r < grid.size(); r++) {
for (int c = 0; c < grid[0].size(); c++) {
if (grid[r][c] == '1') {
dfs(grid, r, c);
count++;
}
}
}
return count;
}
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 during DFS or BFS.
- How many times: Each cell is checked once in the nested loops, and each land cell is visited once during DFS.
As the grid size grows, the number of cells to check grows too.
| Input Size (n x m) | Approx. Operations |
|---|---|
| 10 x 10 | About 100 visits |
| 100 x 100 | About 10,000 visits |
| 1000 x 1000 | About 1,000,000 visits |
Pattern observation: The operations grow roughly with the total number of cells, so doubling rows and columns quadruples work.
Time Complexity: O(n * m)
This means the time grows proportionally to the total number of cells in the grid.
[X] Wrong: "DFS runs multiple times for each island, so time is more than O(n*m)."
[OK] Correct: Each cell is visited only once because visited land cells are marked, so total work is still proportional to grid size.
Understanding this helps you explain how to efficiently explore connected areas in grids, a common problem in coding interviews.
"What if the grid was very sparse with few land cells? How would the time complexity change if we used BFS instead of DFS?"
Practice
Solution
Step 1: Understand the problem definition
The problem asks to count distinct islands, where an island is a group of connected '1's horizontally or vertically.Step 2: Clarify what is being counted
We count how many separate clusters of '1's exist, not the total number of '1's or sizes.Final Answer:
Count how many separate groups of connected '1's exist -> Option BQuick Check:
Number of islands = count of connected '1' groups [OK]
- Counting total '1's instead of groups
- Including diagonal connections as connected
- Confusing island size with island count
Solution
Step 1: Understand 2D vector initialization syntax
To create a 2D vector of chars, use vector of vectors: outer vector size = rows, inner vector size = cols.Step 2: Check each option
std::vector grid(rows, std::vector<char>(cols, '0')); correctly creates 'rows' vectors each with 'cols' chars initialized to '0'. Others have wrong types or parameters.Final Answer:
std::vector grid(rows, std::vector<char>(cols, '0')); -> Option AQuick Check:
2D vector init = vector of vectors with sizes [OK]
- Swapping rows and cols sizes
- Using wrong vector types
- Trying to initialize 2D vector with three parameters
std::vector grid = {
{'1','1','0','0'},
{'1','0','0','1'},
{'0','0','1','1'},
{'0','0','0','0'}
};
int countIslands(const std::vector& grid) {
int count = 0;
int rows = grid.size();
int cols = grid[0].size();
std::vector visited(rows, std::vector<bool>(cols, false));
std::queue> q;
int directions[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
for(int i=0; i=0 && nr=0 && ncSolution
Step 1: Identify islands in the grid
Islands are groups of connected '1's. Here, islands are: top-left cluster (3 cells), single '1' at (1,3), and bottom cluster (2 cells at (2,2),(2,3)). Total 3 islands.Step 2: Understand BFS traversal
The BFS marks all connected '1's visited per island, so count increments once per island found.Final Answer:
3 -> Option AQuick Check:
Count islands = 3 [OK]
- Counting diagonal connections as islands
- Missing isolated '1's as separate islands
- Not marking visited correctly causing overcount
void dfs(int r, int c, std::vector& grid) {
int rows = grid.size();
int cols = grid[0].size();
if(r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0')
return;
grid[r][c] = '0';
dfs(r+1, c, grid);
dfs(r-1, c, grid);
dfs(r, c+1, grid);
dfs(r, c-1, grid);
}
int numIslands(std::vector& grid) {
int count = 0;
for(int i=0; iSolution
Step 1: Analyze DFS grid modification
The DFS marks visited cells by changing '1' to '0' in the original grid, modifying input.Step 2: Identify why this is a bug
Modifying input grid may be unintended side effect; better to use a separate visited array to avoid altering input data.Final Answer:
The grid is modified during DFS, which is incorrect -> Option DQuick Check:
Modifying input grid = bug [OK]
- Ignoring that grid is changed in-place
- Assuming no visited tracking needed
- Misreading boundary checks as incorrect
Solution
Step 1: Understand connectivity change
Diagonal connections mean neighbors include 8 directions: up, down, left, right, and 4 diagonals.Step 2: Modify directions array
Add diagonal moves (1,1), (1,-1), (-1,1), (-1,-1) to directions used in BFS or DFS to explore all connected neighbors.Final Answer:
Add diagonal directions (like (1,1), (1,-1), (-1,1), (-1,-1)) to the directions array -> Option CQuick Check:
Include all 8 neighbors for diagonal connectivity [OK]
- Ignoring diagonal neighbors
- Counting only horizontal or vertical neighbors
- Trying to count without traversal
Ready to prove it?
Pass the test and this pattern moves unknown
