我有一個矩陣中的合法鄰居的遞歸洪水填充(合法鄰居是一個具有相同顏色的鄰居),洪水沒有填充數組中的所有合法鄰居。 使用用於測試`米的板是:
遞歸洪水填充 - 檢查邊界
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