Bird
Raised Fist0
DSA Cprogramming

Number of Islands BFS and DFS in DSA C

Choose your learning style10 modes available
Mental Model
We find groups of connected land cells by exploring neighbors until no new land is found, counting each group as one island.
Analogy: Imagine walking through a forest and marking all connected trees as one cluster before moving to the next cluster.
Grid example:
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1

1 = land, 0 = water
Dry Run Walkthrough
Input: grid: [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]
Goal: Count how many separate islands (connected groups of 1s) are in the grid
Step 1: Start at (0,0), find land, begin BFS/DFS to mark connected land
Visited (0,0), (0,1), (1,0), (1,1) marked as visited
Grid:
X X 0 0 0
X X 0 0 0
0 0 1 0 0
0 0 0 1 1
Why: We mark all connected land in this cluster to count one island
Step 2: Move to (0,2), water, skip
No change
Grid:
X X 0 0 0
X X 0 0 0
0 0 1 0 0
0 0 0 1 1
Why: Water cells do not belong to islands
Step 3: At (2,2), find new land, start BFS/DFS to mark connected land
Visited (2,2)
Grid:
X X 0 0 0
X X 0 0 0
0 0 X 0 0
0 0 0 1 1
Why: New island found, mark connected land
Step 4: At (3,3), find new land, start BFS/DFS to mark connected land
Visited (3,3), (3,4)
Grid:
X X 0 0 0
X X 0 0 0
0 0 X 0 0
0 0 0 X X
Why: Third island found, mark connected land
Result:
Final visited grid:
X X 0 0 0
X X 0 0 0
0 0 X 0 0
0 0 0 X X
Number of islands = 3
Annotated Code
DSA C
#include <stdio.h>
#include <stdbool.h>

#define ROWS 4
#define COLS 5

// Directions for neighbors (up, down, left, right)
int directions[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};

void dfs(int grid[ROWS][COLS], bool visited[ROWS][COLS], int r, int c) {
    if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return; // boundary check
    if (visited[r][c]) return; // already visited
    if (grid[r][c] == 0) return; // water cell

    visited[r][c] = true; // mark current land as visited

    for (int i = 0; i < 4; i++) {
        int nr = r + directions[i][0];
        int nc = c + directions[i][1];
        dfs(grid, visited, nr, nc); // explore neighbors
    }
}

int numIslands(int grid[ROWS][COLS]) {
    bool visited[ROWS][COLS] = {{false}};
    int count = 0;

    for (int r = 0; r < ROWS; r++) {
        for (int c = 0; c < COLS; c++) {
            if (grid[r][c] == 1 && !visited[r][c]) {
                dfs(grid, visited, r, c); // mark all connected land
                count++;
            }
        }
    }
    return count;
}

int main() {
    int grid[ROWS][COLS] = {
        {1,1,0,0,0},
        {1,1,0,0,0},
        {0,0,1,0,0},
        {0,0,0,1,1}
    };

    int islands = numIslands(grid);
    printf("Number of islands = %d\n", islands);
    return 0;
}
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) return;
stop if out of grid bounds
if (visited[r][c]) return;
skip if cell already visited
if (grid[r][c] == 0) return;
skip water cells
visited[r][c] = true;
mark current land cell visited
for (int i = 0; i < 4; i++) { dfs(grid, visited, r + directions[i][0], c + directions[i][1]); }
explore all four neighbors recursively
if (grid[r][c] == 1 && !visited[r][c]) { dfs(grid, visited, r, c); count++; }
start DFS for new island and increment count
OutputSuccess
Number of islands = 3
Complexity Analysis
Time: O(R*C) because each cell is visited once during DFS
Space: O(R*C) for the visited array and recursion stack in worst case
vs Alternative: Compared to BFS, DFS uses recursion stack; both have similar time but BFS uses queue for iteration
Edge Cases
Empty grid (all water)
Returns 0 islands as no land is found
DSA C
if (grid[r][c] == 1 && !visited[r][c]) {
Grid with one big island (all land)
Returns 1 island after marking all cells visited
DSA C
visited[r][c] = true;
Grid with multiple small islands separated by water
Counts each separate cluster correctly
DSA C
dfs(grid, visited, r, c);
When to Use This Pattern
When you see a grid and need to count connected groups, use DFS or BFS to explore neighbors and mark visited cells to avoid double counting.
Common Mistakes
Mistake: Not marking visited cells, causing infinite loops or overcounting
Fix: Always mark cells as visited before exploring neighbors
Mistake: Checking neighbors outside grid boundaries
Fix: Add boundary checks before accessing neighbors
Summary
Counts how many connected groups of land cells (islands) are in a grid using DFS or BFS.
Use when you need to find clusters or connected components in a 2D grid.
The key is to explore all connected neighbors from each unvisited land cell to mark one whole island.

Practice

(1/5)
1. What does the "Number of Islands" problem ask you to find in a grid of '1's and '0's?
easy
A. Find the longest path of '1's in the grid
B. Count how many groups of connected '1's (islands) are in the grid
C. Calculate the total number of '0's in the grid
D. Replace all '1's with '0's in the grid

Solution

  1. 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.
  2. Step 2: Identify what is counted

    We count each cluster of adjacent '1's (connected horizontally or vertically) as one island.
  3. Final Answer:

    Count how many groups of connected '1's (islands) are in the grid -> Option B
  4. Quick Check:

    Number of islands = count of connected '1' groups [OK]
Hint: Islands = groups of connected '1's in grid [OK]
Common Mistakes:
  • Counting individual '1's instead of groups
  • Including diagonal connections as connected
  • Counting '0's instead of '1's
2. Which of the following is the correct way to start a DFS function to explore neighbors in a grid for the Number of Islands problem in C?
easy
A. int dfs(int row, int col, char* grid)
B. int dfs(char grid[][], int row, int col)
C. void dfs(int row, int col, int grid[][])
D. void dfs(int row, int col, char** grid, int rows, int cols)

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    void dfs(int row, int col, char** grid, int rows, int cols) -> Option D
  4. Quick Check:

    Correct DFS signature includes grid pointer and size [OK]
Hint: DFS needs grid pointer, indices, and grid size [OK]
Common Mistakes:
  • Using incorrect grid parameter type
  • Missing grid size parameters
  • Wrong return type for DFS
3. Given the grid:
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?
medium
A. 3
B. 2
C. 1
D. 4

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Count connected '1' groups = 3 [OK]
Hint: Count connected '1' clusters visually [OK]
Common Mistakes:
  • Counting diagonal '1's as connected
  • Missing isolated single '1's
  • Misreading grid rows or columns
4. In the following DFS code snippet for Number of Islands, what is the bug?
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);
}
medium
A. It does not check for visited cells, causing infinite recursion
B. It modifies the grid, which is not allowed
C. It correctly marks visited cells by setting '1' to '0', no bug
D. It misses diagonal neighbors in DFS

Solution

  1. Step 1: Analyze how visited cells are handled

    The code sets grid[r][c] = '0' to mark visited cells, preventing revisiting.
  2. 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.
  3. Final Answer:

    It correctly marks visited cells by setting '1' to '0', no bug -> Option C
  4. Quick Check:

    Mark visited by changing '1' to '0' is correct [OK]
Hint: Mark visited by changing '1' to '0' is valid [OK]
Common Mistakes:
  • Thinking grid modification is always wrong
  • Expecting separate visited array
  • Confusing diagonal neighbors as required
5. You have a grid with 1000 rows and 1000 columns filled mostly with '0's and a few scattered '1's forming small islands. Which approach is best to efficiently count islands and why?
hard
A. Use BFS with a queue to avoid deep recursion and handle large grid efficiently
B. Use DFS with recursion because it is simpler and faster for large grids
C. Use DFS but do not mark visited cells to save memory
D. Count '1's directly without traversal to save time

Solution

  1. Step 1: Consider grid size and recursion limits

    A 1000x1000 grid is large. Recursive DFS may cause stack overflow due to deep recursion.
  2. 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.
  3. Step 3: Check other options for correctness

    DFS without marking visited causes infinite loops. Counting '1's directly misses island grouping.
  4. Final Answer:

    Use BFS with a queue to avoid deep recursion and handle large grid efficiently -> Option A
  5. Quick Check:

    Large grid + avoid recursion overflow = BFS [OK]
Hint: Use BFS to avoid recursion limits on large grids [OK]
Common Mistakes:
  • Using recursive DFS causing stack overflow
  • Not marking visited cells causing infinite loops
  • Counting '1's without grouping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard