这是Hackerrank问题的java解决方案。
我知道它不是优化的,有人能帮我重构和优化吗?
任务计算6×6阵列中每个沙漏的沙漏和,然后打印最大沙漏和。“沙漏和”定义为该模式掩码选择的数组中任意7个条目的总和:✓输入格式有6行输入,其中每一行包含描述2D数组的6个空格分隔的整数;每个条目在包含的范围内-9到9。输出格式打印数组中最大(最大)沙漏和。样本输入1 1 1 0 0 0 1 1 0 0 0 2 4 4 0 0 0 2 0 0 0 2 4 0样本输出19
解决方案:
public class TestHourGlass {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int hourGlassSum[] = new int[16];
int pos = 0;
//Reads data from user input and store in 6*6 Array
for (int arr_i = 0; arr_i < 6; arr_i++) {
for (int arr_j = 0; arr_j < 6; arr_j++) {
arr[arr_i][arr_j] = in.nextInt();
}
}
//Find each possible hourGlass and calculate sum of each hourGlass
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
hourGlassSum[pos] = calculateHourGlassSum(arr, i, i + 2, j, j + 2);
pos++;
}
}
System.out.println(findmax(hourGlassSum));
}
/**
* @param arr
* @param pos1 - Row startPoint
* @param pos2 - Row endPoint
* @param pos3 - column startPoint
* @param pos4 - column endPoint
* @return
*/
public static int calculateHourGlassSum(int arr[][], int pos1, int pos2, int pos3, int pos4) {
int sum = 0;
int exclRowNum = pos1 + 1;
int exclColNum1 = pos3;
int exclColNum2 = pos4;
for (int arr_i = pos1; arr_i <= pos2; arr_i++) {
for (int arr_j = pos3; arr_j <= pos4; arr_j++) {
sum = sum + arr[arr_i][arr_j];
}
}
sum = sum - (arr[exclRowNum][exclColNum1] + arr[exclRowNum][exclColNum2]);
return sum;
}
/**
* @param arr
* @return max elem of Array
*/
public static int findmax(int arr[]) {
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= max)
max = arr[i];
}
return max;
}
}发布于 2017-06-08 11:39:17
你真的需要一个数组来存储所有的总和吗?你可以跟踪最大金额,因为这是你最终要返回的。
int max = 0;
for(int row = 0; row < GRID_SIZE-2; row++){
for(int col = 0; col < GRID_SIZE-2; col++){
int temp = hourGlassSum(arr, row, col);
max = Math.max(temp, max);
}
}
System.out.println(max);我也同意安吉拉的观点,但我认为左上角的位置应该是中间的:
public static int hourGlassSum (int[][] arr, int row, int col){
return arr[row][col] + arr[row][col+1] + arr[row][col+2]
+ arr[row+1][col+1]
+ arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2];
}我的编辑悲伤地自动缩进
public static int hourGlassSum(int[][] arr, int row, int col) {
return arr[row][col] + arr[row][col + 1] + arr[row][col + 2]
+ arr[row + 1][col + 1]
+ arr[row + 2][col] + arr[row + 2][col + 1] + arr[row + 2][col + 2];
}发布于 2017-06-07 19:51:44
对于6X6的网格。就像@Ronan提到的,有(6-2)^2个沙漏,因为如果你看一下时间玻璃的中心,在d位置。它仅从(1,1)到(4,4)的位置有效。
因此,在主函数中,您可以首先扫描数字并存储在int arrundefined中。
然后从(1,1)到(4,4),我调用以下函数:
public static int hourGlassSum (int[][] arr, int row, int col){
int sum = arr[row][col]+ arr[row-1][col-1]+ arr[row-1][col]+ arr[row-1][col+1]
+ arr[row+1][col-1]+arr[row+1][col]+ arr[row+1][col+1];
return sum;
}注意,上面函数中的int行和int col是沙漏中心的位置,在图中的位置是d。在我个人看来,这比你的calculateHourGlassSum()更容易理解
https://codereview.stackexchange.com/questions/165192
复制相似问题