Note: I would prefer an algorithm or code in c language, thank you in advance.
Suppose I have a 5x5 2D array.
00, 00, 01, 01, 00
01, 00, 01, 01, 00
01, 00, 00, 01, 01
01, 01, 00, 00, 00
01, 00, 00, 01, 01
Criteria for grouping :- All the 1s (01s) in the array that are connected to each other from up, down, left, right or diagonally belongs to the same group.
Now, I want to group all the 1s (01s) together without recursion in such a way that my array looks like:-
00, 00, 02, 02, 00
01, 00, 02, 02, 00
01, 00, 00, 02, 02
01, 01, 00, 00, 00
01, 00, 00, 03, 03
At last I output how many groups there are. Here, I output 3.
Say I find the connection from one index position, suppose I am at i=1 and j=0. Now using nested loops I can find all connections from the position I am at.
for(int i=-1; i<2; i++){
for(int j=-1; j<2; j++){
}}
But how do I find the connections from a connection? Say I find all connections from i=1, j=0. If I found a 1 at i=1,j=1 then how do I continue my search again? Here recursion seems easy but how should I do this without recursion?
Here is what I have so far. I have no time bound limit so I am doing this stupidly.
void printImgArray(int array[L][L])
{
printf("------ Image Contents -------\n");
int i, j;
for (i=0; i<L; i++)
{
for (j=0; j<L; j++)
printf("%02d, ",array[i][j]);
printf("\n");
}
printf("-----------------------------\n");
}
int checkIndex(int i, int j){
return i >= 0 && j>=0 && i< L && j< L;
}
int colorNonRecursively(int image[L][L]) {
int copyArray[L][L] = {0};
int i, j, new_i, new_j;
int counter = 1;
for(i=0; i<L; i++){
for(j=0; j<L; j++){
for(new_i=-1; new_i<2; new_i++){
for(new_j=-1; new_j<2; new_j++){
if(copyArray[i][j] != 1 && image[i][j] != 0){
copyArray[i][j] = 1;
image[i][j] = counter;
if(checkIndex(i+new_i, j+new_j)){
if(copyArray[i+new_i][j+new_j] != 1 &&
image[i+new_i][j+new_j] != 0){
copyArray[i+new_i][j+new_j] = 1;
image[i+new_i][j+new_j] = counter;
}
}
}
}
}
counter++;
}
}
int main(){
int cellImg[L][L]={{0,0,1,1,0},\
{1,0,1,1,0},\
{1,0,0,1,1},\
{1,1,0,0,0},\
{1,0,0,1,1}};
printImgArray(cellImg);
colorNonRecursively(cellImg);
printImgArray(cellImg);
return 0;
}
Input 2D array:-
00, 00, 01, 01, 00
01, 00, 01, 01, 00
01, 00, 00, 01, 01
01, 01, 00, 00, 00
01, 00, 00, 01, 01
Output 2D array:-
00, 00, 03, 04, 00
06, 00, 08, 09, 00
11, 00, 00, 14, 15
16, 17, 00, 00, 00
21, 00, 00, 24, 25
Here I can see that my counter is placed at the right location but grouping is not done correctly. I know this code has a running time of N^4 but in my case it does not matter so please ignore it. How can I group these correctly so that I have this array as output?
Output 2D array(that should be):-
00, 00, 02, 02, 00,
01, 00, 02, 02, 00,
01, 00, 00, 02, 02,
01, 01, 00, 00, 00,
01, 00, 00, 03, 03,