I have a BufferedImage whit some shapes drawn down on it, I'm trying to fill those whit a random color; I have made a method whit recursion to do this job, and it does it, but:
- It's painfully slow
- It requires a lot of stack memory (I had to scale it up to 1GB to avoid problems)
I heard that is always possible to avoid recursion but I can't come up whit a more efficient way to do it, any help would be appreciated
The method returns an ArrayList of int[] which represent all the pixel that I have to fill (then I color those pixel by pixel) It start from a random point that hasn't be colored yet.
I would like to have a result similar to the one that we can have using the instrument "fill" on Microsoft Paint
Here's the code of the method that find all points in a section:
ArrayList<int[]> populatesSection(ArrayList<int[]> section, int[] is) {
int[][] neighbors=new int[4][2];
int i;
neighbors[0][0]=is[0];
neighbors[0][1]=is[1]+1;
neighbors[1][0]=is[0]-1;
neighbors[1][1]=is[1];
neighbors[2][0]=is[0];
neighbors[2][1]=is[1]-1;
neighbors[3][0]=is[0]+1;
neighbors[3][1]=is[1];
toBeColored.remove(contains(toBeColored, is));
section.add(is);
for(i=0;i<neighbors.length;i++)
if(isValid(neighbors[i]) && contains(toBeColored, neighbors[i])>=0 && contains(section, neighbors[i])<0)
populatesSection(section, neighbors[i]);
return section;
}
initial BufferedImage:
colored BufferedImage: