2012-04-03 50 views
0

我在這裏要做的是計算由隨機黑色(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。我在這裏想念什麼?我有種感覺,我不必要地循環。

+1

這是爲了做作業嗎? – 2012-04-03 00:49:21

+1

你必須使用遞歸嗎? – twain249 2012-04-03 00:50:20

+0

這不是家庭作業,我也不必使用遞歸。我只是想到了。如果有更好的解決方案,我很想知道。 – noMAD 2012-04-03 00:52:00

回答

2

這裏沒有遞歸

for(int i = 0; i < mat.length; i++) { 
    for(int j = 0; j < mat[i].length; j++) { 
     if(mat[i][j] == 1) { 
      if(i < mat.length - 1 && mat[i+1][j] == 1) { 
       count++; 
      } 
      if(j < mat[i].length - 1 && mat[i][j+1] == 1) { 
       count++; 
      } 
    } 
} 
1

一個解決方案,我不認爲遞歸是正確的答案,你只能是前進了一大步深(找到相鄰值)。取而代之的是循環查看右側和下側的元素。不要像上面提到的那樣擡頭或離開,以免重複計數。然後它是簡單的:

for (i=0; i<max; i++) 
    for (j=0; j<max; j++) 
    if (array[i][j] == 1){ 
     if (i<max-1 && array[i+1][j] == 1) count++; 
     if (j<max-1 && array[i][j+1] == 1) count++; 
    }