2017-03-01 109 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

非常感谢! –