I am trying to create an algorithm that could populate an int array in C #. Basically, as a filling tool in MS Paint, I have a color, and if I select the (x, y) coordinates in the array, it will replace all the neighbors with the same initial color with the new color.
Example:
[0,0,0] [0,1,0] [1,1,0]
If I put 3 in (0,0), the array will become:
[3,3,3] [3,1,3] [1,1,3]
So, I tried this in recursive mode, but it works, but not all the time. In fact, I sometimes have a "Stack Overflow" error (seems appropriate). Here is my code, it would be great if you could tell me what is wrong :)
public int[,] fill(int[,] array, int x, int y, int initialInt, int newInt) { if (array[x, y] == initialInt) { array[x, y] = newInt; if (x < array.GetLength(0) - 1) array = fill(array, (x + 1), y, initialInt, newInt); if (x > 0) array = fill(array, (x - 1), y, initialInt, newInt); if (y < array.GetLength(1) - 1) array = fill(array, x, (y + 1), initialInt, newInt); if (y > 0) array = fill(array, x, (y - 1), initialInt, newInt); } return array; }
Thanks!