I need to create a program that receives as input an array size (up to 300 per 300) and the array values that will be stored (it can be only 1 or 0). I must determine the number of "islands" (clusters of 1) formed and display for the user. I can only use the stdio.h library. At the end of the program two examples of inputs and the expected results follow.
So far I have only been able to store the array that the user places as input and determine the "borders" (parts where the 1 is close to 0) and replace these values with 2.
Here's what I've been able to do so far:
#include <stdio.h>
int main() {
char a, b; /*este char nao tem funçao no programa ainda*/
int w, h;/*largura e altura da matriz respectivamente que o usuario irá mandar como input*/
int image[300][300];
int i, j;
int island;
scanf("%c%c %d %d", &a, &b, &w, &h);
printf("%d %d \n", w, h);
for ( i = 0; i < h; i++ ) {
for ( j = 0; j < w; j++ )
{
scanf ("%d", &image[ i ][ j ]);
}
}
/*armazena a matriz do usuario*/
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
if (image[i][j] == 1) {
if (i == 0) {
if (image[i][j + 1] == 0 || image[i][j - 1] == 0 || image[i - 1][j - 1] == 0 || image[i - 1][j + 1] == 0) {
image[i][j] = 2;
}
}
if (j == 0) {
if (image[i + 1][j] == 0 || image[i][j + 1] == 0 || image[i + 1][j + 1] == 0 || image[i][j - 1] == 0 || image[i + 1][j - 1] == 0) {
image[i][j] = 2;
}
}
if (j > 0 && j < w && i > 0 && i < h) {
if (image[i + 1][j] == 0 || image[i][j + 1] == 0 || image[i + 1][j + 1] == 0 || image[i - 1][j] == 0 || image[i][j - 1] == 0 || image[i - 1][j - 1] == 0 || image[i - 1][j + 1] == 0 || image[i + 1][j - 1] == 0) {
image[i][j] = 2;
}
}
}
}
}
/*printa a matriz do usuario para debugar*/
for ( i = 0; i < h; i++ ) {
printf("\n");
for ( j = 0; j < w; j++ )
{
printf ("%d ", image[ i ][ j ]);
}
}
/*parte que deveria contar o numero de ilhas*/
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
if (image[i][j] == 2) {
island++;
}
}
}
printf("\n%d", island);
return 0;
}
Examples of user input:
P1
40 22
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0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