我有一个矩阵中的合法邻居的递归洪水填充(合法邻居是一个具有相同颜色的邻居),洪水没有填充数组中的所有合法邻居。 使用用于测试`米的板是:
递归洪水填充 - 检查边界
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.
输出为:
4000
0900
0900
0900
编辑 如果我真的改变地图到:
int[][] map={{4,0,0,0},
{4,4,0,0},
{0,4,0,0},
{0,4,0,0}};
输出将是:
4000
4900
0900
0900
两个左4号需要太填补。 和我的递归函数是:
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);
}
更改代码
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);
}
现在的输出是:
9000
9900
0900
0400
看起来是正确的,你期望输出什么?如果你期望(0,0)处的4也被填充,它不会是因为你的算法只计算直接相邻的单元格,而不是邻居的对角线。 –
好吧,如果你可以看到第1行<= 0,如果我改变它> =我得到了stackoverflow ..这是它的正确的条件,不是吗? – MrAlmonds