2017-03-01 108 views
0

爲什麼我的解決方案無法正常工作?混淆2D陣列

這是一個練習2D陣列的練習,顯然我已經在undeerstanding他們失敗了。 輸入是創建一個方法,它可以在Array [] []中查找最大的沙漏形整數數量。數組的大小將始終爲6x6,因此對於循環是x < 4和y < 4,整數值將從-9到9,這就是爲什麼我的結果變量以-256開頭(如果我從0開始,數組已滿的負值難道不工作)

樣品輸入

1 1 1 0 0 0 
0 1 0 0 0 0 
1 1 1 0 0 0 
0 0 2 4 4 0 
0 0 0 2 0 0 
0 0 1 2 4 0 

即導致輸出的沙漏形狀

2 4 4 
    2 
1 2 4 

樣本輸出

19 

我的錯輸出

13 

這裏的方法:

公共類解決方案{ 公共靜態INT biggestHourglass(INT [] []緩衝液){

 int result = -256; 
     int currentSize = 0; 

     for (int x=0; x<4; x++){ 
      for (int y=0; y<4; y++){ 
       currentSize = (buffer[x][y+2] + buffer[x+1][y+2] + buffer[x+2][y+2] 
             + buffer[x+1][y+1] 
         + buffer[x][y] + buffer[x+1][y] + buffer[x+2][y]); 
       if (currentSize > result) { result = currentSize;} 
      } 
     } 

     return result; 
    } 
} 

然後在主用我biggestHourglass()方法。

public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    int arr[][] = new int[6][6]; 
    for(int i=0; i < 6; i++){ 
     for(int j=0; j < 6; j++){ 
      arr[i][j] = in.nextInt(); 
     } 
    } 
    System.out.println(Solution.biggestHourglass(arr)); 
} 
} 

我resulst不匹配,期望,我不知道我做了錯誤的。請不要粗魯,我還在學習。謝謝!

+1

您應該指定什麼是 「整數最大的沙漏形數」 是指。 –

+0

看看示例輸入,如果你看看這個二維數組的左上角,'1的創建類似沙漏形狀,頂部1 1 1,然後中間1和底部1 1 1,這是一個沙漏形狀我是什麼需要找到,我會盡力在我的問題中解釋它,謝謝你的反饋 –

+0

但這是一個相當鬆散的定義。如果我在第一行和第三行有六個1,並且我有兩個1,以第二行爲中心,那麼這是否值得考慮(因爲一般形狀會相似)。我可以有超過3行嗎?它們應該包含什麼來算作「沙漏形」。 –

回答

1
public class Solution { 
    public static int biggestHourglass(int[][] buffer){ 

     int result = -256; 
     int currentSize = 0; 

     for (int x=0; x<4; x++){ 
      for (int y=0; y<4; y++){ 
       currentSize = (buffer[x+2][y] + buffer[x+2][y+1] + buffer[x+2][y+2] 
             + buffer[x+1][y+1] 
         + buffer[x][y] + buffer[x][y+1] + buffer[x][y+2]); 
       if (currentSize > result) { result = currentSize;} 
      } 
     } 

     return result; 
    } 
} 

我還沒有檢查過,但看起來像你搞砸了x和y軸。

所以基本上你了:

[x][_][x] 
[x][x][x] 
[x][_][x] 

形狀代替:

[x][x][x] 
[_][x][_] 
[x][x][x] 
+0

是的,它的工作原理!非常感謝。 –

1
currentSize = (buffer[x][y] + buffer[x][y+1] + buffer[x][y+2] 
            + buffer[x+1][y+1] 
        + buffer[x+2][y] + buffer[x+2][y+1] + buffer[x+2][y+2]); 
      if (currentSize > result) { result = currentSize;} 

*尺寸計算應如上,你要添加

(0, 0)+(0,1)+(0,2)

+ (1,1) + 

(2,0)+(2,1)+(2,2)

在你第一次迭代

等*

+0

非常感謝! –