Bird
Raised Fist0
DSA Cprogramming~10 mins

Number of Islands BFS and DFS in DSA C - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start BFS from the given cell.

DSA C
void bfs(char** grid, int r, int c, int row, int col, int** visited) {
    int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    int queue[10000][2];
    int front = 0, rear = 0;
    queue[rear][0] = row;
    queue[rear][1] = col;
    rear++;
    visited[row][col] = 1;

    while (front < rear) {
        int currRow = queue[front][0];
        int currCol = queue[front][1];
        front++;

        for (int i = 0; i < 4; i++) {
            int newRow = currRow + directions[i][0];
            int newCol = currCol + directions[i][1];

            if (newRow >= 0 && newRow < r && newCol >= 0 && newCol < c &&
                grid[newRow][newCol] == '1' && visited[newRow][newCol] == 0) {
                queue[rear][0] = newRow;
                queue[rear][1] = newCol;
                rear++;
                visited[newRow][newCol] = [1];
            }
        }
    }
}
Drag options to blanks, or click blank then click option'
A2
B1
C-1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Marking visited cells as 0 which means unvisited.
Not marking visited cells at all causing infinite loops.
2fill in blank
medium

Complete the code to check if the current cell is land and unvisited before DFS.

DSA C
void dfs(char** grid, int r, int c, int row, int col, int** visited) {
    if (row < 0 || row >= r || col < 0 || col >= c ||
        grid[row][col] == '0' || visited[row][col] == [1]) {
        return;
    }
    visited[row][col] = 1;

    dfs(grid, r, c, row - 1, col, visited);
    dfs(grid, r, c, row + 1, col, visited);
    dfs(grid, r, c, row, col - 1, visited);
    dfs(grid, r, c, row, col + 1, visited);
}
Drag options to blanks, or click blank then click option'
A0
B2
C1
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for visited cells incorrectly as 0 instead of 1.
Not checking boundaries causing out-of-range errors.
3fill in blank
hard

Fix the error in the main function to count islands using DFS.

DSA C
int numIslands(char** grid, int r, int c) {
    int count = 0;
    int** visited = malloc(r * sizeof(int*));
    for (int i = 0; i < r; i++) {
        visited[i] = calloc(c, sizeof(int));
    }

    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            if (grid[i][j] == '1' && visited[i][j] == 0) {
                dfs(grid, r, c, i, j, visited);
                count[1];
            }
        }
    }

    for (int i = 0; i < r; i++) {
        free(visited[i]);
    }
    free(visited);
    return count;
}
Drag options to blanks, or click blank then click option'
A--
B+=
C++
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using -- which decreases count incorrectly.
Using = which resets count.
4fill in blank
hard

Fill both blanks to complete BFS traversal and mark visited cells.

DSA C
void bfs(char** grid, int r, int c, int row, int col, int** visited) {
    int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    int queue[10000][2];
    int front = 0, rear = 0;
    queue[rear][0] = row;
    queue[rear][1] = col;
    rear++;
    visited[row][col] = 1;

    while (front < rear) {
        int currRow = queue[front][0];
        int currCol = queue[front][1];
        front++;

        for (int i = 0; i < 4; i++) {
            int newRow = currRow + directions[[1]][0];
            int newCol = currCol + directions[[2]][1];

            if (newRow >= 0 && newRow < r && newCol >= 0 && newCol < c &&
                grid[newRow][newCol] == '1' && visited[newRow][newCol] == 0) {
                queue[rear][0] = newRow;
                queue[rear][1] = newCol;
                rear++;
                visited[newRow][newCol] = 1;
            }
        }
    }
}
Drag options to blanks, or click blank then click option'
Ai
B0
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using different indices for row and column causing wrong neighbors.
Using constants instead of loop variable i.
5fill in blank
hard

Fill all three blanks to create a DFS call that explores neighbors correctly.

DSA C
void dfs(char** grid, int r, int c, int row, int col, int** visited) {
    if (row < 0 || row >= r || col < 0 || col >= c ||
        grid[row][col] == '0' || visited[row][col] == 1) {
        return;
    }
    visited[row][col] = 1;

    int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (int i = 0; i < 4; i++) {
        dfs(grid, r, c, row [1] directions[i][[2]], col [3] directions[i][[2]], visited);
    }
}
Drag options to blanks, or click blank then click option'
A+
B-
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using - instead of + causing wrong neighbor positions.
Using same index for both row and column offsets.

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