Context
Given a 2D Array, :
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
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values.
Task
Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Input Format
There are lines of input, where each line contains space-separated integers describing 2D Array ; every value in will be in the inclusive range of to .
Constraints
Output Format
Print the largest (maximum) hourglass sum found in .
Sample Input
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
Sample Output
19
Explanation
contains the following hourglasses:
1 1 1 1 1 0 1 0 0 0 0 0
1 0 0 0
1 1 1 1 1 0 1 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0
1 1 0 0
0 0 2 0 2 4 2 4 4 4 4 0
1 1 1 1 1 0 1 0 0 0 0 0
0 2 4 4
0 0 0 0 0 2 0 2 0 2 0 0
0 0 2 0 2 4 2 4 4 4 4 0
0 0 2 0
0 0 1 0 1 2 1 2 4 2 4 0
The hourglass with the maximum sum () is:
2 4 4
2
1 2 4
풀이
배열과 관련된 문제는 역시 index를 잘 살펴봐야 한다.
2차원배열인데 좌표를 적어가면서 하면 쉽게 해결법을 찾을 수 있다.
1. 첫 좌표
[0,0] + [0,1] + [0,2]
+ [1,1] +
[2,0] + [2,1] + [2,2]
2. 두 번째 좌표
[0,1] + [0,2] + [0,3]
+ [1,2] +
[2,1] + [2,2] + [2,3]
이런 방식으로 계속 진행될 것이다.
행과 열을 순회해야 하기 때문에 for문안에 for문이 필요하다.
먼저 0행을 기준으로 돌기 때문에 바깥쪽 for문은 행
안쪽 for문은 렬을 나타낸다.
Math.math(p1, p2) 함수의 경우 p1 과 p2중 더 큰 숫자를 저장한다.
input의 조건을 보면 음수(-)가 들어갈 수도 있기 때문에
섣불리 max에 넣을 최초값을 0으로 잡지말고 Integer.MIN_VALUE로 잡자.
static int array2D(int[][] arr) {
/*
* Write your code here.
*/
int sum = Integer.MIN_VALUE;
for(int i = 0; i < arr.length -2; i++){
for(int j = 0; j < arr[0].length - 2; j++){
int temp =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];
System.out.println(temp);
sum = Math.max(sum, temp);
}
}
return sum;
}
'DataStructure > Array' 카테고리의 다른 글
Add One To Number (0) | 2018.10.15 |
---|---|
Min Steps in Infinite Grid (0) | 2018.10.15 |
Left Rotation (0) | 2018.04.19 |
Dynamic Array (0) | 2018.04.19 |
Arrays - DS (0) | 2018.04.13 |