我在這裏要做的是計算由隨機黑色(0)和白色(1)塊組成的方形棋盤上的相鄰白色塊(2的數量) 。白色塊必須在i+1,j
|| i-1,j
|| i,j+1
|| i,j-1
。技術上的對角線不計算在內。我已經提供瞭如下的例子:討論棋盤遊戲的遞歸代碼
[1 0 1]
[1 1 0]
[0 1 0]
這裏count == 3
(0,0)(1,0) and (1,0)(1,1) and (1,1)(2,1)
這裏是我的代碼:
public int count = 0;
boolean count(int x, int y, int[][] mat)
{
if(x<0 || y<0)
return false;
if(mat[x][y] == 0)
return false;
for(int i = x; i<mat.length; i++)
{
for(int j = y; j<mat[0].length; j++)
{
if(mat[i][j] == 1)
{
mat[i][j] = 0;
if(count(i-1,j,mat))
count++;
if(count(i,j-1,mat))
count++;
if(count(i+1,j,mat))
count++;
if(count(i,j+1,mat))
count++;
}
}
}
return true;
}
的什麼,我想在這裏做簡短的解釋:我要對發現1點的在板上,當我找到一個時,我將它更改爲0,並檢查它的上,下,左,右爲1。這繼續下去,直到我找不到相鄰的1。我在這裏想念什麼?我有種感覺,我不必要地循環。
這是爲了做作業嗎? – 2012-04-03 00:49:21
你必須使用遞歸嗎? – twain249 2012-04-03 00:50:20
這不是家庭作業,我也不必使用遞歸。我只是想到了。如果有更好的解決方案,我很想知道。 – noMAD 2012-04-03 00:52:00