I Have a recursive flood fill of legal neighbours in matrix ( legal neighbour is a neighbour with same color), the flood is not filling all the legal neighbours in the array.
the board I`m using for testing is :
int[][] map={{4,0,0,0},
{0,4,0,0},
{0,4,0,0},
{0,4,0,0}};
fill(map,1,1,9,4);// calling to function.
the output is :
4000
0900
0900
0900
Edit If i`m changing the map to:
int[][] map={{4,0,0,0},
{4,4,0,0},
{0,4,0,0},
{0,4,0,0}};
The output will be:
4000
4900
0900
0900
The two left 4 number need to be filled too.
and my recursive function is :
public static void fill(int[][] map, int row, int col, int color,int oldColor)
{
System.out.println("row is: "+row+"col is:"+col);
if ((row <= 0) || (row >= map.length) || (col <= 0) || (col >= map.length) ) return;
if(map[row][col]==color)
return;
if(map[row][col]==oldColor)
{
map[row][col]=color;
}
if(col+1<=map.length)
fill(map, col+1, row,color,oldColor);
if((col-1)<=0)
fill(map,col-1, row,color,oldColor);
if(row+1<=map.length)
fill(map, col, row+1,color,oldColor);
if((row-1)<=0)
fill(map, col, row-1,color,oldColor);
}
Changing the code
public static void fill(int[][] map, int row, int col, int color,int oldColor) {
System.out.println("row is: "+row+"col is:"+col);
if ((row < 0) || (row > map.length) || (col < 0) || (col > map.length) || map[row] [col]!=oldColor ) return;
if(map[row][col]==color)
return;
if(map[row][col]==oldColor)
{
map[row][col]=color;
}
fill(map, col, row-1,color,oldColor);
fill(map, col+1, row,color,oldColor);
fill(map, col, row+1,color,oldColor);
fill(map,col-1, row,color,oldColor);
}
The output is now:
9000
9900
0900
0400