144k views
2 votes
Write a function, in the programming language of your choice, which finds contiguous regions (or "islands") in a matrix where all values in the island are greater than a threshold (but not necessarily the same). The function should take a threshold, a minimum island size, and an arbitrarily sized matrix as inputs. The function should output a matrix (same size as the input matrix) of booleans. Do not wrap around matrix edges. Corner neighbors are not sufficient for island continuity. For example, if the the inputs are: threshold = 5, min island size = 3, and matrix = [4, 4, 4, 2, 2; 4, 2, 2, 2, 2; 2, 2, 8, 7, 2; 2, 8, 8, 8, 2; 8, 2, 2, 2, 8]. Then the output would be [0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 0, 0, 1, 1, 0; 0, 1, 1, 1, 0; 0, 0, 0, 0, 0].

User Carlos F
by
4.5k points

1 Answer

1 vote

Answer:

#include <stdio.h>

int main()

{

int threshold = 5;

int i,j;

int matrix[5][5] = {{4, 4, 4, 2, 2},

{4, 2, 2, 2, 2},

{2, 2, 8, 7, 2},

{2, 8, 8, 8, 2},

{8, 2, 2, 2, 8}};

int row=(sizeof(matrix)/sizeof(matrix[0])); // length of row

int column=(sizeof(matrix)/sizeof(matrix[0][0]))/row; // length of column

printf("Input matrix value:\\");

for(i=0; i <5; i++)

{

for(j=0; j<5; j++)

{

printf("%d ", matrix[i][j]);

}

printf("\\");

}

printf("\\");

for(i=0; i<column; i++)

{

for(j=0; j<column; j++)

{

if ( (j == 0) || (j == column-1) ) // print 0 for first and last element of every row

printf("%d ", 0);

else

{

if(matrix[i][j] > threshold) // veify whether the element is more than threshold

{

printf("%d ",1);

}

else

{

printf("%d ", 0);

}

}

}

printf("\\");

}

return 0;

}

User Kolin Krewinkel
by
4.1k points