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 number of cells affect the work done by BFS or DFS?
Analyze the time complexity of the following code snippet.
void dfs(char** grid, int r, int c, int rows, int cols) {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] != '1')
return;
grid[r][c] = '0';
dfs(grid, r + 1, c, rows, cols);
dfs(grid, r - 1, c, rows, cols);
dfs(grid, r, c + 1, rows, cols);
dfs(grid, r, c - 1, rows, cols);
}
int numIslands(char** grid, int rows, int cols) {
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j, rows, cols);
count++;
}
}
}
return count;
}
This code counts islands by running DFS on each land cell and marking connected land as visited.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: DFS visits each cell connected to land once.
- How many times: Each cell is visited at most once during DFS or the main loops.
As the grid size grows, the number of cells to check grows too.
| Input Size (n = rows * cols) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows roughly in direct proportion to the number of cells.
Time Complexity: O(rows * cols)
This means the time needed grows linearly with the total number of cells in the grid.
[X] Wrong: "DFS runs for each land cell separately, so time is O((rows*cols)^2)"
[OK] Correct: Each cell is visited only once because visited cells are marked, so DFS does not repeat work.
Understanding how DFS or BFS explores grids efficiently is a key skill for many problems involving connected components.
"What if the grid was very sparse with few land cells? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand the problem definition
The problem asks to find how many separate groups of connected '1's exist in the grid. Each group is called an island.Step 2: Identify what is counted
We count each cluster of adjacent '1's (connected horizontally or vertically) as one island.Final Answer:
Count how many groups of connected '1's (islands) are in the grid -> Option BQuick Check:
Number of islands = count of connected '1' groups [OK]
- Counting individual '1's instead of groups
- Including diagonal connections as connected
- Counting '0's instead of '1's
Solution
Step 1: Check parameter types for grid and indices
The grid is a 2D array of characters, passed as char** grid. Row and col are integers. Rows and cols are needed to check boundaries.Step 2: Verify function signature matches common DFS pattern
void dfs(int row, int col, char** grid, int rows, int cols) correctly uses void return type (no return needed), takes row, col, grid pointer, and grid size parameters.Final Answer:
void dfs(int row, int col, char** grid, int rows, int cols) -> Option DQuick Check:
Correct DFS signature includes grid pointer and size [OK]
- Using incorrect grid parameter type
- Missing grid size parameters
- Wrong return type for DFS
char* grid[] = {"11000", "11000", "00100", "00011"};
int rows = 4, cols = 5;What is the number of islands found by a correct BFS or DFS solution?
Solution
Step 1: Visualize the grid and connected '1's
Grid rows:
Row 0: 1 1 0 0 0
Row 1: 1 1 0 0 0
Row 2: 0 0 1 0 0
Row 3: 0 0 0 1 1
Islands are groups of connected '1's horizontally or vertically.Step 2: Count islands by grouping connected '1's
Island 1: Top-left block (positions (0,0),(0,1),(1,0),(1,1))
Island 2: Middle single '1' at (2,2)
Island 3: Bottom-right block (positions (3,3),(3,4))
Total islands = 3.Final Answer:
3 -> Option AQuick Check:
Count connected '1' groups = 3 [OK]
- Counting diagonal '1's as connected
- Missing isolated single '1's
- Misreading grid rows or columns
void dfs(int r, int c, char** grid, int rows, int cols) {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0')
return;
grid[r][c] = '0';
dfs(r+1, c, grid, rows, cols);
dfs(r-1, c, grid, rows, cols);
dfs(r, c+1, grid, rows, cols);
dfs(r, c-1, grid, rows, cols);
}Solution
Step 1: Analyze how visited cells are handled
The code sets grid[r][c] = '0' to mark visited cells, preventing revisiting.Step 2: Check if this approach is valid and complete
Marking visited by changing '1' to '0' is a common and valid method. The code checks boundaries and stops recursion correctly.Final Answer:
It correctly marks visited cells by setting '1' to '0', no bug -> Option CQuick Check:
Mark visited by changing '1' to '0' is correct [OK]
- Thinking grid modification is always wrong
- Expecting separate visited array
- Confusing diagonal neighbors as required
Solution
Step 1: Consider grid size and recursion limits
A 1000x1000 grid is large. Recursive DFS may cause stack overflow due to deep recursion.Step 2: Evaluate BFS advantages for large grids
BFS uses an explicit queue and avoids deep recursion, making it safer and efficient for large grids.Step 3: Check other options for correctness
DFS without marking visited causes infinite loops. Counting '1's directly misses island grouping.Final Answer:
Use BFS with a queue to avoid deep recursion and handle large grid efficiently -> Option AQuick Check:
Large grid + avoid recursion overflow = BFS [OK]
- Using recursive DFS causing stack overflow
- Not marking visited cells causing infinite loops
- Counting '1's without grouping
Ready to prove it?
Pass the test and this pattern moves unknown
