My goal is to find connected components in a 2D array for example finding connected '*'
chars below.

      x x x x x x
      x x x x x x
      x x * * x x
      x x * * x x
      x x x * * x
      * x x x x x


There are two connected '*' group in this example. First group is composes of six '*' located closer to middle and the second group composes only one '*' char located in the left bottom corner.

Do to this I generally implement a recursive algorithm which repeat calling the same function by checking all neighbors around the current index. I generally end up with something like :

void foo( int row, int col)
{
    //Do something here like caching the index

    if ( twoDimensionData[row - 1][col] == '*')
       foo(row- 1, col);
    else if ( twoDimensionData[row + 1][col] == '*')
       foo(row+ 1, col);
    else if ( twoDimensionData[row - 1 ][col - 1] == '*')
       foo(row - 1, col - 1);

//..... I need 5 more of this bad boys I mean if checks
}

Is there any better way to achieve this with cool std functions like enumerate or iota without needing to write eight if checks?

Reply via email to