Iterative flood fill

Hi,

I’ve got a recursive flood fill to create caves, but if cave large, stack overflow. So, I’ve been looking at iterative using a queue:


public class IterativeFloodFill {

	static char[][] m = { 
			{'x','x','x','c','x' },
			{'x','x','x','c','x' },
			{'x','x','x','c','x' },
			{'x','x','x','c','x' },
			{'x','x','x','c','x'},		
	};
	
	
	private static void fill(int x, int y, char target, char replace)
	{
		if(m[x][y] == replace) return;

		Queue<Character> q = new LinkedList(); 			
		q.add(m[x][y]);  
		while(!q.isEmpty()) {  
			q.remove(); 
			if( m[x][y]!= replace && m[x][y]==target) 
			{
				m[x][y] = replace;  
				q.add(m[x][y+1]);
				q.add(m[x][y-1]);
				q.add(m[x+1][y]);				
				q.add(m[x-1][y]);
			}
		}
	}
		
public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int x=1; x<4;x++)
			for(int y=1;y<4;y++)
				fill(x,y,'c','w');

	
		for(int x=1; x<=4;x++,System.out.println())
			for(int y=1;y<=4;y++)
				System.out.print(m[x][y]);

	}



Now the obvious problem above would give arrayIndexOutOfBounds exception as y would become -1, and so would x as I start x,y off as 0.

I’m taking it you need to start off someplace else and call the above in a forloop?

Thanks