ProgrammingVery hardCompetitive coding (CP)

How many islands does this 4-connected flood-fill count find in the 3 by 3 grid "101", "010", "101"? Compute with the program.

How many islands does this 4-connected flood-fill count find in the 3 by 3 grid "101", "010", "101"? Compute with the program.
#include <stdio.h>
char g[3][4] = {"101", "010", "101"};
void sink(int r, int c) {
    if (r < 0 || c < 0 || r > 2 || c > 2 || g[r][c] != '1') return;
    g[r][c] = '0';
    sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
}
int main(void) {
    int islands = 0;
    for (int r = 0; r < 3; r++)
        for (int c = 0; c < 3; c++)
            if (g[r][c] == '1') { islands++; sink(r, c); }
    printf("%d", islands);
}
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: C. 5

The five 1 cells are at the corners and the centre, and no two of them touch orthogonally, so each one is its own island.

More C Programming questions

Exams that ask this topic