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);
}- A. 4
- B. 3
- C. 5
- 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
- How many of these statements are true when x = 255? Count them with this program. c #include <stdint.h> #include <stdio.h> int main(void)…
- What is printed? c #include <stdio.h> int main(void) { unsigned a = 3; int b = -5; printf("%d", (a + b) > 0); }
- What is printed? c #include <stdio.h> #include <string.h> int main(void) { sizet n = 0; printf("%d", n - 1 > 100); }
- What is printed? c #include <stdio.h> int pal(const char s, int n) { int l = 0, r = n - 1; while (l < r) { if (s[l] != s[r]) return 0…
- What is printed? c #include <stdio.h> int main(void) { int m[3][5]; for (int i = 0; i < 3; i++) for (int j = 0; j < 5; j++) m[i][j] = i 5…
- What is printed? c #include <stdio.h> void swap(int a, int b) { int t = a; a = b; b = t; } int main(void) { int x = 1, y = 2; int p = &x…