【发布时间】:2012-12-19 21:01:16
【问题描述】:
我在矩阵中有一个合法邻居的递归洪水填充(合法邻居是具有相同颜色的邻居),洪水没有填充数组中的所有合法邻居。
我用于测试的板是:
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 行= 我会得到 stackoverflow.. 这是适合它的条件,不是吗?
标签: java recursion flood-fill