DAY 1
0

# 2D Array - DS

### 題目描述

``````1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
``````

``````a b c
d
e f g
``````

``````-9 -9 -9  1 1 1
0 -9  0  4 3 2
-9 -9 -9  1 2 3
0  0  8  6 6 0
0  0  0 -2 0 0
0  0  1  2 4 0
``````

``````-63, -34,  -9, 12,
-10,   0,  28, 23,
-27, -11,  -2, 10,
9,  17,  25, 18
``````

``````0 4 3
1
8 6 6
``````

### 輸入限制

• input 會是個 6*6 的二維陣列
• 陣列中每個元素的值介於 9 ~ -9

### 範例

``````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
``````

19

### 解題概念：

``````a b c
d
e f g
``````

top : 3 個元素 a b c
middle : 中間一個元素 d
buttom : 3 個元素 e f g

``````arr[i][j]    arr[i][j+1]     arr[i][j+2]
arr[i+1][j+1]
arr[i+2][j]  arr[i+2][j+1]   arr[i+2][j+2]
``````

``````a b c
d
e f g
``````

### 程式碼

``````package hourglass;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Solution {

// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int max = 7 * -9;

for(int i = 0; i < 6; i++) {
for(int j = 0; j < 6; j++) {
if((i+2) < 6 && (j+2) < 6) { // 避免 outbound of index
int top = arr[i][j] + arr[i][j+1] + arr[i][j+2];
int middle = arr[i+1][j+1];
int bottom = arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2];
int sum = top + middle + bottom;
if(sum > max) {
max = sum;
}

}
}
}
return max;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int[][] arr = new int[6][6];

for (int i = 0; i < 6; i++) {
String[] arrRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int j = 0; j < 6; j++) {
int arrItem = Integer.parseInt(arrRowItems[j]);
arr[i][j] = arrItem;
}
}

int result = hourglassSum(arr);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}

``````