I know that a similar answer has been asked many times, but my case isn't that simple.
I have a recursive method which can call itself 4 times ("Worst case"). I'm trying hard to avoid recursion since it leads to a StackOverFlowException but I cannot find a way to replace it with a while loop or something similar.
Is this even possible? As far as I've come with my knowledge, you can only move in one direction using a while loop instead of "flowing" in all directions (depth-first-search in reality).
Here is the code:
private static void searchNeighboringPixels(int x, int y, int[][] arr) {
arr[y][x] = 2;
if (x+1 < arr[y].length && arr[y][x+1] == 1) {
searchNeighboringPixels(x+1, y, arr);
//...do other things
}
if (x-1 > 0 && arr[y][x-1] == 1) {
searchNeighboringPixels(x-1, y, arr);
//...do other things
}
if (y+1 < arr.length && arr[y+1][x] == 1) {
searchNeighboringPixels(x, y+1, arr);
//...do other things
}
if (y-1 > 0 && arr[y-1][x] == 1) {
searchNeighboringPixels(x, y-1, arr);
//...do other things
}
}
What I am doing here:
- In a "binary picture" (here in the example it's turned into a 2D-int Array) I'm looking for black pixels around a specific one until I got all connected black pixels.
- Black has the value of 1, white has the value of 0. Pixels that I already visited will be set to value 2 (for later processing).
- This algorithm makes a "depht-first search" until all connected black pixels (side-by-side) have been found